gpt4 book ai didi

ruby-on-rails - Rails 4 - 插入重复的 ActiveRecord 数据

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:52 25 4
gpt4 key购买 nike

我开发了一些对象,下面是我的代码。

if ObjectRating.where(user_id: current_user.id, object_id: @object.id).present?
rating = ObjectRating.where(user_id: current_user.id, object_id: @object.id).first
if rating.update_attributes(rating_params)
@jsonResult.object = rating
else
@jsonResult.status = false
@jsonResult.message = "Please Retry"
end
else
rating = @object.object_ratings.new(rating_params)
rating.user_id = current_user.id

if rating.save
@jsonResult.object = rating
else
@jsonResult.status = false
@jsonResult.message = "Please Retry"
end
end

评分参数是

private
def rating_params
params.require(:object_rating).permit(:rating)
end

它运行良好,但有时会向数据库中插入重复数据。


+----------------------------------------------------------+
| id, object_id , user_id, rating, created_at, updated_at |
+----------------------------------------------------------+
| 1, 100, 200, 8 ,2015-06-26 10:52:34, 2015-06-26 10:52:48 |
| 2, 100, 200, 8 ,2015-06-26 10:52:34, 2015-06-26 10:52:34 |
| 3, 120, 230, 8 ,2015-06-26 10:54:32, 2015-06-26 10:54:32 |
+----------------------------------------------------------+

ID 1, 2 是同一个对象。

我在保存到 Controller 之前检查过,为什么它为下一个创建重复记录?

最佳答案

您可以添加以下列object_id、user_id、rating 的索引。创建迁移,例如,

add_index :object_ratings, [:object_id , :user_id, :rating], unique: true

关于ruby-on-rails - Rails 4 - 插入重复的 ActiveRecord 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065116/

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