简体   繁体   English

唯一性验证无效

[英]Uniqueness Validation not working

I am trying to apply validation of uniqueness to the field name custom_link. 我试图将唯一性验证应用于字段名称custom_link。 But it is allowing to add same values in the field. 但这允许在字段中添加相同的值。 Following is my model: 以下是我的模型:

class Gallery < ActiveRecord::Base
....
validates :custom_link, uniqueness: true
....
end

This is my code of controller: 这是我的控制器代码:

def update
      respond_to do |format|
      if @gallery.update(gallery_params)
        format.html { redirect_to galleries_galleryhome_path(id: params[:id]), notice: 'Gallery was successfully updated.' }
        format.json { render :show, status: :ok, location: @gallery }
      else
        format.html { render :edit }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end   end
private:

def gallery_params
      params.require(:gallery).permit(:name, :shoot_date, :release_date, :expiration_date, :archive,:gallery_layout_id, :contact_id,:status, :cover_url,:gallery_photo_id, photos_attributes: [:image]).merge(brand_id: current_brand.id,user_id: current_user.id)
    end

Getting no idea why it is not working. 不知道为什么它不起作用。 Can anyone help me? 谁能帮我?

Try considering case. 尝试考虑大小写。

validates :custom_link, uniqueness: {case_sensitive: false}

Can you provide an example of what is allowed to be created more than once? 您能否举一个例子说明允许多次创建的内容?

When are you creating the same value, on new creation, on update of an existing object, etc? 什么时候创建相同的值,新创建的对象,现有对象的更新等?

You should add a unique index in your DB, as stated in: http://guides.rubyonrails.org/active_record_validations.html#uniqueness 您应该在数据库中添加唯一索引,如以下所述: http : //guides.rubyonrails.org/active_record_validations.html#uniqueness

2.11 uniqueness This helper validates that the attribute's value is unique right before the object gets saved. 2.11唯一性此助手在保存对象之前验证属性的值是否唯一。 It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. 它不会在数据库中创建唯一性约束,因此可能发生两个不同的数据库连接为您打算唯一的列创建两个具有相同值的记录。 To avoid that, you must create a unique index on both columns in your database. 为避免这种情况,您必须在数据库的两列上创建唯一索引。 See the MySQL manual for more details about multiple column indexes. 有关多列索引的更多详细信息,请参见MySQL手册。

Add a migration with that constraint as follow: 添加具有该约束的迁移,如下所示:

rails g migration add_uniqueness_to_custom_link

Then write the new index: 然后编写新索引:

self.change
   add_index :galleries, :custom_link, unique: true
end

And finally: rake db:migrate 最后: rake db:migrate

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

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