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. On Thursday, November 6, 2014 7:22:42 AM UTC-8, Matt jones wrote: > > > On Nov 6, 2014, at 12:33 AM, Danny Sperry <danny....@gmail.com > <javascript:>> 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 > > > -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-core+unsubscr...@googlegroups.com. To post to this group, send email to rubyonrails-core@googlegroups.com. Visit this group at http://groups.google.com/group/rubyonrails-core. For more options, visit https://groups.google.com/d/optout.