【发布时间】:2015-10-07 07:04:32
【问题描述】:
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 的唯一性。但我不喜欢在控制器操作中进行验证的想法。
【问题讨论】:
标签: ruby-on-rails postgresql simple-form cocoon-gem