ruby-on-rails – accepted_nested_attributes_for验证
我正在使用Rails 2.3.8和accepts_nested_attributes_for.
我有一个简单的类别对象,它使用awesome_nested_set来允许嵌套类别. 对于每个类别,我想要一个称为代码的唯一字段.这对于每个级别的类别是唯一的.含义父类别将具有唯一代码,子类别在其自己的父类别中将是唯一的. 例如: code name 1 cat1 1 sub cat 1 2 cat2 1 sub cat 1 2 sub cat 2 3 cat3 1 sub1 这可以在没有验证过程的情况下工作,但是当我尝试使用以下内容时 这不起作用,因为父母尚未保存. 这是我的模型: class Category < ActiveRecord::Base acts_as_nested_set accepts_nested_attributes_for :children,:reject_if => lambda { |a| a[:name].blank? },:allow_destroy => true default_scope :order => "lft" validates_presence_of :code,:name,:is_child validates_uniqueness_of :code,:scope => :parent_id end 我已经想到了一种不同的方法来做到这一点并且它非常接近工作,问题是我无法检查子类别之间的唯一性. 在第二个例子中,我以“is_child”的形式嵌入了一个隐藏字段,以标记该项是否为子类.这是我的这个模型的例子: class Category < ActiveRecord::Base acts_as_nested_set accepts_nested_attributes_for :children,:is_child #validates_uniqueness_of :code,:scope => :parent_id validate :has_unique_code attr_accessor :is_child private def has_unique_code if self.is_child == "1" # Check here if the code has already been taken this will only work for # updating existing children. else # Check code relating to other parents result = Category.find_by_code(self.code,:conditions => { :parent_id => nil}) if result.nil? true else errors.add("code","Duplicate found") false end end end end 这非常接近.如果有一种方法可以在accepts_nested_attributes_for下的reject_if语法中检测重复代码,那么我就会在那里.这一切似乎都过于复杂,并希望提高建议.我们希望继续在一个表单中添加类别和子类别,因为它可以加快数据输入速度. 更新: 解决方法
代替
validates_uniqueness_of :code,:scope => :parent_id 尝试 validates_uniqueness_of :code,:scope => :parent 除此之外,您还需要在Category类中进行设置: has_many :children,:inverse_of => :category # or whatever name the relation is called in Child 使用inverse_of会在保存之前设置children变量parent,并且有可能它会起作用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |