这是我目前的代码:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
validates :name, :presence => true, :uniqueness => { :scope => :parent_id, :case_sensitive => false }
end
我的问题是,当我这样做时:
Parent.create(params)
唯一性验证仅在创建任何子项之前进行检查。在添加每个孩子后,它永远不会再次检查。有没有办法在每个被添加的孩子之间调用验证?
如果没有ActiveRecord方法,我将在父级上编写自己的验证方法。但我想知道是否有一种“更容易”的方式。
这是日志:
Child Exists (0.4ms)
Child Exists (0.2ms)
Parent Exists (0.3ms)
SQL (0.6ms) INSERT INTO "parents"
SQL (0.3ms) INSERT INTO "children"
SQL (0.3ms) INSERT INTO "children"
答案 0 :(得分:1)
# app/validators/products_name_uniqueness_validator.rb
class ProductsNameUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << "Products names must be unique" unless value.map(&:name).uniq.size == value.size
end
end
# app/models/shop.rb
class Shop < ActiveRecord::Base
validates :products, :products_name_uniqueness => true
end