2016-06-24 24 views
0

我正在尝试验证字段名称custom_link的唯一性。但它允许在该字段中添加相同的值。 以下是我的模型:唯一性验证不起作用

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

这是我的控制器代码:

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 

获取不知道为什么它不工作。谁能帮我?

+0

你阅读有关的文档'唯一性'可以和不可以做? – Zabba

+0

嗨,你可以请你分享你的控制器代码,因为你已经写了它应该工作的写入语法。 –

+0

@Bharat Soni,我已经分享了我的控制器的代码 – Vishal

回答

0

尝试考虑大小写。

validates :custom_link, uniqueness: {case_sensitive: false} 

您能提供一个允许多次创建的示例吗?

你什么时候创建相同的值,在新创建,更新现有对象等?

+0

Thanx回复Keith。我也试过这个。但它不起作用。我正在尝试在更新时创建相同的值。 – Vishal

0

你应该在你的数据库添加一个唯一索引,如说:http://guides.rubyonrails.org/active_record_validations.html#uniqueness

2.11独特 这帮助验证该属性的值是唯一正确的对象被保存之前。它不会在数据库中创建唯一性约束,因此可能会出现两个不同的数据库连接为您打算唯一的列创建两个具有相同值 的记录。为避免这种情况,您必须在您的数据库的两列上创建一个唯一索引 。有关多列索引的更多详细信息,请参见MySQL 手册。

添加迁移与约束如下:

rails g migration add_uniqueness_to_custom_link 

然后写新的索引:

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

最后:rake db:migrate