How to call associations dynamically in ruby?

I'm trying to fetch associations of a model dynamically. For ex;

model1 has_many model2s
model1 has_many model3s

normally i can do x.model2s or x.model3s. But what if i dont know which association is wanted. Is there any snippet like : x["model2s"] to call associations dynamically?

Thanks Çağdaş.

Answers


Yes, you can do x.send("model#{i}s") assuming you have the number saved in i or just x.send(foo) if you have the full name as string or symbol saved in foo.

Documentation:


I think this is safer as it limits to association methods only:

x.association("model#{i}s").scope

Need Your Help

Edit text file in place using C++

c++ text

I have a text file which I am adding tags to in order to make it XML readable. In order for our reader to recognize it as valid, each line must at least be wrapped in tags. My issue arises because