的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
唯一性。但我不喜歡驗證發生在控制器操作中的想法。
而且我在嵌套模式人性化的錯誤信息,像這樣。我添加了'save'方法,調用'super'和'rescue ActiveRecord :: RecordNotUnique' –