has_association? method on ActiveRecord

About a month ago I ran into a case where I needed to know if an AR object’s association exists dynamically. I was building a CMS Engine.

I thought maybe this was a one off, but last week I found out my co-worker also had a need for this in the CMS he was building. So I’ve come to the community to see if this is something we think should be added into ActiveRecord.

I originally solved for this quite naively with the following solution

def is_association?(attribute)
respond_to?(attribute) && !attribute_names.include?(attribute.to_s)
end

``

and after trying to actually solve it in ActiveRecord I discovered reflections. I think this is easily solved with something like the following method inside lib/active_record/assocations.rb or lib/active_record/relation.rb

def has_association?(name)

reflections.include? name

end

``

I’m new to contributing to open source and have been developing with Rails for about a year so any and all questions, comments, criticism is welcome.

Thanks!

I’m not certain where this would be useful, since every time I’ve needed to check for an association’s existence it was as a warmup to actually doing something with the reflection object.

As an example, this code:

if has_association?(:foobar)

refl = reflect_on_association(:foobar)

could just as well be written:

refl = reflect_on_association(:foobar)

if refl

Can you discuss why has_association? would be useful in your code?

—Matt Jones

Wouldn’t this encourage breaking dependency inversion principle?

I think you’re right, before digging into active record I didn’t even know about reflections.

I’ve been using rails for about a year and the wording is odd to me. We have has_attribute? and it seemed to me like there would just be a has_assocation? to go along with it. I think has_association? would end up just being an extension of reflect_on_association that returns a boolean.

refl = reflect_on_association(:foobar)

if refl

In my use case I’m overriding simple_form and am auto detecting if the passed attribute/association param is an attribute or an association, I don’t really need the returned reflection, I just need to know if it exists or not.

I’m very new to all of active records modules and am not sure where this method belongs. I’m not sure if your question was in reference to my “original naive implementation” or just about the proposal in general.