Dynamically get rails association

If I have the association name as a string, is there a way to get the handle of the association object?

For instance:

o = Order.first 

o.customer will provide me with the customer object to which this order belongs.

If I have:

 o = Order.first relationship = 'customer' 

I would like to do something like:

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

I know that eval is a terrible option, and I should avoid it. What is the best way to do this (since eval is not working in this example).

I had this job:

 customer = o.association(relationship) 

Later I learned that the association is not part of the public API and should not be used. Because when I took the line of code, I had a higher page (which referred to this relation), it stopped working.

Any ideas would be great!

+4
source share
3 answers

How about this?

 customer = o.send(relationship) 
+16
source

You can use try() , which will allow you to handle any undefined method errors if the relationship does not exist.

 relationship = 'customer' foo = 'foo' customer = o.try(relationship) # > [ # [0] #<Customer... customer = o.try(foo) # > nil 

vs send() :

 customer = o.send(relationship) # > [ # [0] #<Customer... customer = o.send(foo) # > NoMethodError: undefined method `foo' for #<Order... 
+3
source

For those who are afraid to use send :

 o.association(relationship).scope 
0
source

Source: https://habr.com/ru/post/1489334/


All Articles