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:
# 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