-1

我正在尝试确保以一致的方式保存玩家 ID 的顺序,以便我们可以对它们进行复合索引。玩家 ID 在 before_validation 回调结束时和验证处理程序中切换,但在 before_save 中恢复为旧值,并使用预切换值保存到数据库中。我如何确保正确的排序使其进入数据库?

class Game < ActiveRecord::Base

  belongs_to :player_0, :class_name => "User", :foreign_key => "player_0_id", :inverse_of => :games
  belongs_to :player_1, :class_name => "User", :foreign_key => "player_1_id", :inverse_of => :games
  before_validation :ensure_player_order

private

def ensure_player_order
    if self.player_0_id.nil?
      self.player_1_id = self.player_0_id
      self.player_1_id = nil
    elsif !self.player_1_id.nil?
      ids = [self.player_0_id,self.player_1_id]
      low_id = ids.min
      high_id = ids.max

      self.player_0_id = User.find(low_id)
      self.player_1_id = User.find(high_id)
    end
 end
end
4

1 回答 1

0

由于 player_0 和 player_1 使用关联,因此您必须更新关联,而不是与关联配对的外国 id(我认为这与 ActiveModel::Dirty 拉一些恶作剧有关,但我不确定)。所以将 ensure_player_order 更改为。

def ensure_player_order
    if self.player_0.nil?
      self.player_1 = self.player_0
      self.player_1 = nil
    elsif !self.player_1.nil?
      low = self.player_0.id < self.player_1.id  ? self.player_0 : self.player_1
      high = self.player_0.id < self.player_1.id  ? self.player_1 : self.player_0

      self.player_0 = low
      self.player_1 = high
    end
    true
  end
于 2013-02-19T03:08:30.007 回答