开发者

Rails: Make different references to a DB row refer to the same Ruby object

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:

  1. Is there already a plugin or gem to do this?
  2. Are there good reasons why I shouldn't do this?
  3. 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜