Rails:has_one关联在更改时使has_many关联无效

时间:2013-05-05 16:06:51

标签: ruby-on-rails null polymorphism has-one

我是Rails的新手,我确信我可能在概念上做错了什么,但我仍然在努力寻找根本原因(以及解决方案)。

我有一个GamePlayer模型

class GamePlayer < ActiveRecord::Base
    attr_accessible :name, :points
    before_save :set_defaults

    validates :name, :presence => true

    belongs_to :game
    belongs_to :currentPlayer, :polymorphic => true

    protected

    def set_defaults 
        self.points ||= 0
    end
end

游戏模型

class Game < ActiveRecord::Base

  PLAYING       = 0
  FINISHED      = 1

  STATUSES = {
    PLAYING      => 'Playing',
    FINISHED     => 'Finished'
  }

  attr_accessible :status, :target
  before_validation :set_defaults

  validates_inclusion_of :status, :in => STATUSES.keys, 
    :message => "{{value}} must be in #{STATUSES.values.join ','}"

  validates :target, :presence => true
  validate :minimum_players

  has_many :gamePlayers
  has_one  :currentPlayer, :class_name => "GamePlayer"
  has_many :challenges, :through => :answers
  has_many :answers

  # just a helper method for the view
  def status_name
    STATUSES[status]
  end

  def get_unused_challenge
    Challenge.offset(rand(Challenge.count)).first
  end

  def get_next_player

    self.gamePlayers.each_with_index do |player, index|
      if player == currentPlayer
        if index == self.gamePlayers.length - 1
          self.currentPlayer = self.gamePlayers[0]
        else
          self.currentPlayer = self.gamePlayers[index+1]
        end
        break
      end
    end

  end

  protected

  def set_defaults 
    self.status ||= PLAYING
    self.currentPlayer ||= self.gamePlayers[0]
  end

  def minimum_players
    errors.add(:gamePlayers, "The minimum number of players is 2") if gamePlayers.length < 2
  end
end

这个想法是游戏有玩家,它只有一个CurrentPlayer(反过来)。

当我执行get_next_player时,我在日志中看到当前玩家正在从游戏中分离

UPDATE "game_players" SET "game_id" = NULL, "updated_at" = '2013-05-05 15:47:51.707978' WHERE "game_players"."id" = 37

当我只更改currentPlayer时,它正在改变GamePlayers关联。

我不知道我做错了什么以及为什么会这样。

提前致谢

0 个答案:

没有答案