Rails accepts_nested_attributes_ for validation on a transactional object

I am afraid from a few hours to make the validation of nested attributes work in my rails application. A small caveat is that I have to check nested attributes dynamically based on their parent attributes, since the amount of information required changes over time depending on where the parent element process is located.

So here is my setup: I have a parent with many different related models, and I want to check subsequent nested attributes every time I save the parent. Given the fact that validations change dynamically, I had to write my own validation method in the model:

class Parent < ActiveRecord::Base
  attr_accessible :children_attributes, :status
  has_many :children
  accepts_nested_attributes_for :children
  validate :validate_nested_attributes
  def validate_nested_attributes
    children.each do |child|
      child.descriptions.each do |description|
        errors.add(:base, "Child description value cant be blank") if description.value.blank? && parent.status == 'validate_children'
      end
    end
  end
end


class Child < ActiveRecord::Base
  attr_accessible :descriptions_attributes, :status
  has_many :descriptions
  belongs_to :parent
  accepts_nested_attributes_for :descriptions
end

update_attributes , . , , -, rails , , . , , , , .

:

parent = Parent.create({:status => 'validate_children', :children_attributes => {0 => {:descriptions_attributes => { 0 => {:value => 'Not blank!'}}}})
  #true
parent.update_attributes({:children_attributes => {0 => {:descriptions_attributes => { 0 => {:value => nil}}}})
  #true!! / since child.value.blank? reads the database and returns false
parent.update_attributes({:children_attributes => {0 => {:descriptions_attributes => { 0 => {:value => 'Not blank!'}}}})
  #false, same reason as above

, . "", , . , , -, .

- , ? , , - , / , , - .

!

, , , , :

class Parent < ActiveRecord::Base
  [...]
  has_many :descriptions, :through => :children
  [...]
  def validate_nested_attributes
    descriptions.each do |description|
      [...]
    end
  end
end

- , . , , , , .

, .

+5
1

, validates_associated

​​Child

validates :value, :presence => true, :if => "self.parent.status == 'validate_children'"
+2

All Articles