简体   繁体   English

创建前检查记录是否存在

[英]Check if record exists before creation

I have a subscribe method in my controller 我的控制器中有一个订阅方法

  def subscribe

    @subscription = current_user.subscriptions.create(params[:subscription])
    @subscription.title = @stream.title
    @subscription.save

    redirect_to stream_path(@stream)

  end

Before I set the subscription title to the stream title, how can I check if a subscription already exists with the same title? 在将订阅标题设置为流标题之前,如何检查具有相同标题的订阅是否已存在?

Like so : 像这样:

current_user.subscriptions.where(title: @stream.title).present?

But assuming you only want to save it if it is not included elsewhere you can do this : 但是假设您只想保存它(如果它不包含在其他地方),您可以这样做:

if current_user.subscriptions.where(title: @stream.title).blank?
  @subscription.title = @stream.title
  @subscription.save
end

An elegant way to perform this is to add the logic to your controller so that it validates uniqueness ( and also prevents race conditions ) : 执行此操作的一种好方法是将逻辑添加到控制器中,以验证唯一性(并防止出现竞争情况):

class Subscription < ActiveRecord::Base
   validates_uniqueness_of :title, scope: :user
end

And then you can check validation in model.save ( again, assuming you don't want it to save if it shares the same title ) 然后您可以在model.save中检查验证(再次,假设您不希望它共享相同的标题,则保存它)

To help you out, the suggestion by @Sergio Tulentsev basically means you create a unique index on a column in your db, like this: 为了帮助您, @Sergio Tulentsev的建议基本上意味着您在数据库的列上创建唯一索引,如下所示:

#db/migrate/[timestamp]_new_migration.rb
add_index :table, :column, unique: true

This creates an index on your data table , which basically means you cannot make any duplicate data in it. 这将在数据表上创建一个索引 ,这基本上意味着您不能在其中创建任何重复数据。 The bottom line - it means you can only insert the data once. 底线-这意味着您只能插入一次数据。

-- -

The save! save! method is there to update your record if it exists already. 如果记录已经存在,有方法可以更新您的记录。 First time I've seen this method, so it's been a good lesson for me. 我第一次见过这种方法,因此对我来说是一个很好的教训。 If you're having problems with it, it will probably be that your database will not have the index you need 如果您遇到问题,则可能是数据库没有所需的index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM