2015-10-07 89 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' –