2015-10-07 145 views
1

的Rails 4.2和PostgreSQL 9.3验证独特的范围

型号关系是:

class Nesting < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :configurator, touch: true 

    validates :product_id, uniqueness: { scope: :configurator } 
end 

class Configurator < ActiveRecord::Base 
    has_many :nestings, dependent: :destroy 
    has_many :products, through: :nestings 

    accepts_nested_attributes_for :nestings, reject_if: :all_blank, allow_destroy: true 
end 

的情况,我创建配置与产品foo,然后尝试更新,以增加产品foo工作正常。我收到错误has_already_taken

但是,当我一次添加两个相同的产品验证不起作用。 Configurator范围内Nesting型号的product_id的唯一性如何验证?

我的意见是非常基础的:

= simple_form_for @configurator, remote: true do |f| 
    = f.simple_fields_for :nestings do |nesting| 
    = render 'nesting_fields', f: nesting 
    = link_to_add_association 'add product', f, :nestings, class: 'btn btn-default' 
    = f.button :submit 

_nesting_fields.html.slim

.nested-fields 
    .form-inline 
    = f.association :product, collection: @products 
    = link_to_remove_association f, class: 'btn btn-default' do 
     .glyphicon.glyphicon-remove 

一个快速的解决方案是在控制器动作参数检查的product_id's唯一性。但我不喜欢验证发生在控制器操作中的想法。

回答

0

Configurator上添加validates_associated可能会有所帮助,但我会为Nesting添加唯一性约束。在迁移:

class AddUniqueIndexToNesting < ActiveRecord::Migration 
    def change 
    add_index :nestings, [:configurator_id, :product_id], unique: true 
    end 
end 

另见:

Rails 3: Uniqueness validation for nested fields_for

Rails - Validate Nested Attributes Uniqueness with scope parent of parent

https://github.com/rails/rails/issues/1572

+1

而且我在嵌套模式人性化的错误信息,像这样。我添加了'save'方法,调用'super'和'rescue ActiveRecord :: RecordNotUnique' –