Rails 3嵌套属性验证无法正常工作

时间:2015-02-09 14:00:05

标签: ruby forms ruby-on-rails-3 validation nested-attributes

我使用rails 3.2和cocoon gem创建新的嵌套字段,并拥有此模型。

ParteDiario.rb

class ParteDiario < ActiveRecord::Base
  has_many :parte_diario_items, dependent: :destroy
  has_many :task_one, through: :parte_diario_items
  accepts_nested_attributes_for :parte_diario_items, :reject_if => lambda { |a| a[:employee_id].blank? and a[:new_employee].blank? }, :allow_destroy => true
  validates_associated :parte_diario_items
end

ParteDiarioItem.rb

class ParteDiarioItem < ActiveRecord::Base
    belongs_to :employee
    belongs_to :task_one, :class_name => 'ParteDiarioTask', :foreign_key => 'task_one_id'
    validates :employee_id, presence: true, if: "new_employee.nil?"
    validates :new_employee, presence: true, if: "employee_id.nil?"
end

ParteDiarioItem有两列: employee_id new_employee (这是一个手动插入名称的字符串)。我们的想法是您可以使用现有员工创建项目,也可以创建new_employee(只需手动编写名称)。如果您创建新员工,则empleado_id为零。这样,在DB中我将拥有employee_id或new_employee_ [name]的每个项目。当其中一个是零时,另一个不应该是。

提交表单时,只发送其中一个字段(当employee_id输入显示给用户时,new_employee输入不是)。我使用cocoon gem来创建新的嵌套字段,一切正常(除了验证)。

使用此语法不起作用。提交带有“&new -employee输入”项目的表单时空白,ParteDiario.valid?是真的。并且应该是假的。

也试过这样的事情,结果相同:

validates :employee_id, presence: true, unless: :new_employee
validates :new_employee, presence: true, unless: :employee_id

有人可以帮我吗?

非常感谢!

2 个答案:

答案 0 :(得分:1)

由于这个问题,我终于找到了答案: Rails validations are not being run on nested model

我不确定原因,但似乎这一行产生了问题

accepts_nested_attributes_for :parte_diario_items, :reject_if => lambda { |a| a[:employee_id].blank? and a[:new_employee].blank? }, :allow_destroy => true

删除:reject_if...让我正确验证模型。

答案 1 :(得分:0)

以下代码可以为您提供帮助:

Validates_presence_of :employee_id, :if => Proc.new{|p| p.new_employee.nil? }
Validates_presence_of :new_employee, :if => Proc.new{ |p| p.employee_id.nil? }