我是Ruby和Rails的新手,請耐心等待。如何防止連接表中的重複記錄
我有兩個模型播放器和獎勵通過has_many通過如下關係加入。我的玩家模型有一個屬性點。當玩家獲得積分時,他們可以獲得獎勵。我想要做的就是在更新前運行的Player模型中添加一個方法,併爲他們下面的點提供適當的獎勵。
但是我想這樣做,如果玩家已經有獎勵它不會被複制,也不會導致錯誤。
class Player < ActiveRecord::Base
has_many :earned_rewards, -> { extending FirstOrBuild }
has_many :rewards, :through => :earned_rewards
before_update :assign_rewards, :if => :points_changed?
def assign_rewards
case self.points
when 1000
self.rewards << Reward.find_by(:name => "Bronze")
when 2000
self.rewards << Reward.find_by(:name => "Silver")
end
end
class Reward < ActiveRecord::Base
has_many :earned_rewards
has_many :players, :through => :earned_rewards
end
class EarnedReward < ActiveRecord::Base
belongs_to :player
belongs_to :reward
validates_uniqueness_of :reward_id, :scope => [:reward_id, :player_id]
end
module FirstOrBuild
def first_or_build(attributes = nil, options = {}, &block)
first || scoping{ proxy_association.build(attributes, &block) }
end
end
嘗試'validates_uniqueness_of:reward_id,範圍:: player_id',(':reward_id:player_id')對必須是uniq – 2014-09-24 03:31:59
@PavittarGill使用您的方法會導致運行時出現語法錯誤。 – Minutiae 2014-09-24 13:27:18
'validates_uniqueness_of:reward_id,scope::player_id' – 2014-09-26 03:23:26