ruby-on-railsassociationsactive-relation

dynamically get rails association


If I have an association name as a string, is there a way I can get a handle on the association object?

For example:

o = Order.first

o.customer will give me the customer object that this order belongs to.

If I have:

o = Order.first
relationship = 'customer'

i would like to do something like:

customer = eval("o.#{relationship}")

I know eval is a terrible option and I should avoid it. What is the best way to do this (as eval does not work in this example).

I did have this working:

customer = o.association(relationship)

I later found out that the association is not part of the public API and should not be used. Because when I took a line of code I had higher up the page off (that referenced that relationship) it stopped working.

Any ideas would be awesome!


Solution

  • What about just doing this?

    customer = o.send(relationship)