On Nov 6, 2014, at 12:33 AM, Danny Sperry <danny.spe...@gmail.com> wrote:

> 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


Attachment: signature.asc
Description: Message signed with OpenPGP using GPGMail

Reply via email to