Forum: Ruby on Rails after_save woes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
60610a080278d5eb88136ee676daa6cd?d=identicon&s=25 Ryan Kohler (Guest)
on 2008-11-25 09:30
(Received via mailing list)
Two models, a game, and a player.  The game should start as soon as
there are enough players in the game
#####################################################

class Game < ActiveRecord::Base
  has_many :players

  should_start
    return players.count >= number_of_players #number_of_players is
defined in the database
  end

  def start
    started = true  #started is a variable defined in the database
    save
  end
end

class Player < ActiveRecord::Base
  belongs_to :game
  after_save :check_game_start

  def check_game_start
    game.start if game.should_start?
  end
end

#########################################
The problem with this code, is that the record has not yet been saved
to the database by the time after_save has been called.  Looking
around the forum, it appears that there is no after_commit callback.
What is the correct way to do this?  Should I change the game to start
at some other point, should I change the RoR code to add the callback
myself, or should I add some hack to make it guess what the new state
of the database is to get it to start?
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-11-25 09:32
(Received via mailing list)
On Nov 25, 12:32 am, Ryan Kohler <Ryan.C.Koh...@gmail.com> wrote:
>   end
>
>   def start
>     started = true  #started is a variable defined in the database
>     save
not the problem here but just as a FYI your start method is a no-op.
you're setting a local variable, not the database attribute.

Fred
This topic is locked and can not be replied to.