Ned Ruggeri
2013-Jun-12 22:02 UTC
`:inverse_of` ignored when inverse is a `has_many` association
Per the [documentation][doc], setting the `:inverse_of` a `belongs_to` association to a `has_many` association is ignored. I''m wondering if there is a reason not to implement this, or if no one has gotten around to it yet. If the latter, I would like to take a stab at it :-) Here''s some example code: ```ruby # app/models/album.rb class Album < ActiveRecord::Base attr_accessible :name has_many :tracks, :inverse_of => :album validates :name, :presence => true end # app/models/track.rb class Track < ActiveRecord::Base attr_accessible :name belongs_to :album, :inverse_of => :tracks validates :album, :name, :presence => true end # Example: a1 = Album.new t1 = a1.tracks.build t1.album # => a1 a1.tracks # => [t1] a2 = Album.new t2 = Track.new t2.album = a2 a2.tracks # => [] ``` The naive expectation is `a2.tracks == [t2]`. My question is why the `inverse_of` is ignored in this case: have I missed something? Is this particularly hard to implement? Is it not a desired feature? I do remember being confused about this (since `inverse_of` is silently ignored) until I found the right documentation. I have heard it suggested that adding `t2` to `a2.tracks` would force fetching `a2.tracks`, causing a DB query. The implication is that `:inverse_of` is ignored for performance reasons. That doesn''t sound right, since `a1.tracks.build` does not force such a query. Thanks very much for reading; any thoughts are much appreciated :-) [doc]: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations.rb#L933 -- 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+unsubscribe@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?hl=en. For more options, visit https://groups.google.com/groups/opt_out.