gpt4 book ai didi

ruby-on-rails - 如何防止连接表中出现重复记录

转载 作者:行者123 更新时间:2023-12-02 04:27:19 26 4
gpt4 key购买 nike

我对 Ruby 和 Rails 还很陌生,所以请耐心等待。

我有两个模型 Player,并且 Reward 通过 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

最佳答案

您还应该在数据库中验证它

在迁移文件中添加以下内容-

add_index :earnedrewards, [:reward_id, :player_id], unique: true

关于ruby-on-rails - 如何防止连接表中出现重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26007207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com