accepts_nested_attributes_for 验证

map*_*ap7 4 validation ruby-on-rails nested-forms

我正在使用 Rails 2.3.8 并接受_nested_attributes_for。

我有一个简单的类别对象,它使用 awesome_nested_set 来允许嵌套类别。

对于每个类别,我想要一个名为 code 的唯一字段。对于每个级别的类别,这将是唯一的。这意味着父类别都将具有唯一的代码,子类别在其自己的父类别中将是唯一的。

例如:

code name
1    cat1
   1 sub cat 1
2    cat2
   1 sub cat 1
   2 sub cat 2
3    cat3
   1 sub1
Run Code Online (Sandbox Code Playgroud)

这无需验证过程即可工作,但是当我尝试使用以下内容时:validates_uniqueness_of :code, :scope => :parent_id

这将不起作用,因为尚未保存父级。

这是我的模型:

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
Run Code Online (Sandbox Code Playgroud)

我已经想到了一种不同的方法来做到这一点,它非常接近工作,问题是我无法检查子类别之间的唯一性。

在第二个示例中,我在名为“is_child”的表单中嵌入了一个隐藏字段,以标记该项目是否为子类别。这是我的这个模型的例子:

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
  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
Run Code Online (Sandbox Code Playgroud)

这非常接近。如果有一种方法可以检测 accepts_nested_attributes_for 下的 reject_if 语法中的重复代码,那么我会在那里。不过,这一切似乎都过于复杂,并希望提出建议以使其更容易。我们希望继续以一种形式添加类别和子类别,因为它可以加快数据输入速度。

更新: 也许我应该使用 build 或 before_save。

hsg*_*ert 5

代替

validates_uniqueness_of :code, :scope => :parent_id
Run Code Online (Sandbox Code Playgroud)

尝试

validates_uniqueness_of :code, :scope => :parent
Run Code Online (Sandbox Code Playgroud)

除此之外,您还需要在 Category 类中设置:

has_many :children, :inverse_of => :category # or whatever name the relation is called in Child
Run Code Online (Sandbox Code Playgroud)

使用 inverse_of 将使 children 变量parent在保存之前设置,并且有可能会起作用。