explainer
explainer

Reputation: 1335

Need programmatic method to detect has_many and has_one relationships

I want to be able to detect the presence of the set of [has_one, has_many, belongs_to] relationships on an ActiveRecord model object. Stated another way, I want to be able to detect from ruby code in the model whether it has one of the above relationships defined.

Is there some clever way, other than the brute force searching of model attributes?

Upvotes: 4

Views: 478

Answers (1)

BaronVonBraun
BaronVonBraun

Reputation: 4293

Take a look at Rails' ActiveRecord::Reflection methods to get what you're looking for.

Model.reflections will return a hash of that model's associations keyed with the association name. Model.reflect_on_all_associations will return an array of those associations, leaving out the named keys.

So, you can do something like this:

Post.reflections.keys  # => [:comments, :author]
Post.reflections[:comments].marco  # => :has_many
Post.reflections[:author].macro    # => :belongs_to
# etc etc

Take a look at the data that is returned from these methods and you should be able to figure out how to do what you want.

Upvotes: 6

Related Questions