我有一个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" endWhat 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 endThis saves a record, with the users logged in id.
My bookmark model:
class Bookmark < ActiveRecord::Base belongs_to :user belongs_to :pin endThanks!
最满意答案
您可以添加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 } endHowever 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: trueUPDATE:
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.
更多推荐
发布评论