如何防止书签表中Rails中的重复记录?(How to prevent duplicate records in Rails within a bookmark table?)

编程入门 行业动态 更新时间:2024-10-27 02:24:34
如何防止书签表中Rails中的重复记录?(How to prevent duplicate records in Rails within a bookmark table?)

我有一个pins表(如标准帖子), users可以'标记'每个pin 。 但是,我想阻止users多次为同一个pin书签,因为它会创建重复的记录。

书签表看起来像:

它不需要实际内容,只需要pin_id和user_id之间的关系。 我想他们是我想避免重复的两个领域。

在我的应用程序中,书签是引脚下的嵌套资源,如下所示:

resources :pins, :path => "pin" do resources :bookmarks, :path => "bookmark" end

什么是避免重复的最佳方法?

我的创建声明是:

def create @pin = Pin.find(params[:pin_id]) @bookmark = @pin.bookmarks.build(:user_id => current_user.id) @bookmark.save end

这将保存记录,用户登录为id。

我的书签模型:

class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :pin end

谢谢!

I have a pins table (like standard posts) and users are able to 'bookmark' each pin. However, I want to stop users from bookmarking the same pin multiple times, as it creates duplicate records.

The bookmark table looks like:

It takes no actual content as such, just a relationship between the pin_id and the user_id. I suppose they are the two fields I'd like to avoid duplication on.

In my app, bookmarks are a nested resource under pins, like so:

resources :pins, :path => "pin" do resources :bookmarks, :path => "bookmark" end

What would be the best way to avoid duplicates?

My create statement is:

def create @pin = Pin.find(params[:pin_id]) @bookmark = @pin.bookmarks.build(:user_id => current_user.id) @bookmark.save end

This saves a record, with the users logged in id.

My bookmark model:

class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :pin end

Thanks!

最满意答案

您可以添加uniqee验证:

class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :pin validates :pin_id, uniqueness: { scope: :user_id } end

但是,您还需要在数据库中设置唯一索引,因为所有验证都可以成为条件竞争的主题。

add_index :bookmarks, [:pin_id, :user_id], unique: true

更新:

正如@engineersmnky所提到的,你应该在create语句中对save方法的结果进行分叉。 目前,无论是否保留书签,您的应用程序都将表现相同,这可能导致用户失去其输入。

You can add uniqee validation:

class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :pin validates :pin_id, uniqueness: { scope: :user_id } end

However you will also need to set a unique index in your database, as all the validations can be a subject of condition race.

add_index :bookmarks, [:pin_id, :user_id], unique: true

UPDATE:

As mentioned by @engineersmnky, you should fork your flow on the result of save method in your create statement. Currently your application will behave the same regardless whether bookmark has been persisted or not which might result in user loosing his input.

更多推荐

本文发布于:2023-04-28 03:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:书签   如何防止   Rails   prevent   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!