Suppose I have the following model relationship:
class Player < ActiveRecord::Base
has_many :cards
end
class Card < ActiveRecord::Base
belongs_to :player
end
I know from this question that Rails will return me a copy of the object representing a database row, meaning that:
p =开发者_运维百科 Player.find(:first)
c = p.cards[0]
c.player.object_id == p.object_id # => false
...and therefore if the Player model modifies self
, and the Card model modifies self.player
in the same request, then the modifications won't take any notice of each other and the last-saved one will overwrite the others.
I'd like to work around this (presumably with some form of caching), so that all requests for a Player with a given id would return the same object (identical object_ids), thereby allowing both models to edit the same object without having to perform a database save-and-reload. I have three questions:
- Is there already a plugin or gem to do this?
- Are there good reasons why I shouldn't do this?
- Can anyone give me some pointers on how to go about doing this?
This is supported in Rails 3.x. You can use the :inverse_of
option for the has_many
association for example. Documentation here (search for :inverse_of
and Bi-directional associations
).
精彩评论