的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' –