Suppose I've got a card-game app, which features a Player
model, which has an actions
integer column; and a Card
model. A player can play a card they own, which costs an action; one particular card grants two actions when it's played.
If I code this as follows:
class Player < ActiveRecord::Base
has_many :cards
def play_card(card)
raise "Not yours!" unless cards.include? card
self.actions -= 1
card.play
save!
end
end
class Card < ActiveRecord::Base
belongs_to :player
def play
player.actions += 2
end
end
... then the net effect of Player#play_card
is to decrement actions
by 1. The only way I've found to make both changes apply to the same object, thereby resulting in a net increment of 1 action, is to define the functions like this:
class Player < ActiveRecord::Base
has_many :cards
def play_card(card)
raise "Not yours!" unless cards.include? card
self.actions -= 1
// Stick that change in the Database
save!
card.play
end
end
class Card < ActiveRecord::Base
belongs_to :player
def play
// Force reload of the player object
player(true).actions += 2
// And save again
player.save!
end
end
But that turns a single database write into two writes and a read! Surely there must be a better way. What am I missing?
In the first version of your code you are loading the same row of the table players but while you are expecting rails to be smart enough to recognize that it has already load this row in memory, rails doesn't work that way. So when you are issuing a +=2 on player it does he +=2 on another instance than the one on which you have done -=1.
i've setup a little example to show that there are too instance of the same row:
So finally as you haven't save the instance with the +=2 applied, there's only the one with the -1 that is saved
UPDATE
You can try to trick rails to use the same instance of player all the way. This is a little bit ugly but it works.
so when you input those commands:
You have the right number of actions in player, and in the logs card is only loaded once:
To sum up the whole thing, I would say that there's something wrong in your code design. If i understand well,what you would like is that every AR instance of a table row is the same object in the ObjectSpace, but I guess that if rails was build that way it would introduce strange behaviors where you could work on half backed object changed in validations and other hooks.