我正在尝试确保以一致的方式保存玩家 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