I'm using rails 3.2 and cocoon gem to create new nested-fields, and have this models.
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 has two columns: employee_id and new_employee (this is a string for inserting a name manually). The idea is that you can create an item using an existing employee, or you can create a new_employee (just writing a name manually). If you create a new employee, empleado_id is nil. That way, in DB i will have every item with an employee_id or with a new_employee_[name]. When one of them is nil, the other shouldn't be.
When submitting the form, only one of those fields is sent (when employee_id input is shown to the user, new_employee input is not). I use cocoon gem to create new nested-fields and everything is working fine (except for validations).
Using this syntax is not working. When submitting a form with an item with 'new_employee input' blank, ParteDiario.valid? is true. And should be false.
Also tried something like this, with same results:
validates :employee_id, presence: true, unless: :new_employee
validates :new_employee, presence: true, unless: :employee_id
Could anyone help me please?
Thanks a lot!