开发者

nested form - how to validate parent model based on inputs on child model?

Have a nested form, the relationship is like so

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection

I have a custom validate method in Inspection which depends on attributes entered for InspectionComponent. How can I validate - InspectionComponent attributes are not saved or available in validation for Inspection.

Thanks!

EDIT: To make things a bit more clear, here's an example of what I'm trying to do.

Inspection has an attribute status. InspectionComponent also has an attribute status.

The Inspection edit form has nested InspectionComponents and one can update each model's status' on this form. @inspection.status should only be able to be marked 'complete' if all @inspection_component.status == 'complete'.

Therefore, when validating @inspection, I must be able to see what the user entered for @inspection_component.status.

Obviously I have access to the params of both instances in the controller however in the model, where validation should occur, I don't see a way of making this happen.

Hopef开发者_运维技巧ully that is clear, thanks.


Ok, a new answer in case the other one I posted is useful to someone else. Specifically for your issue, I think you need something like this:

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

  # we only care about validating the components being complete
  # if this inspection is complete. Otherwise we don't care.
  validate :all_components_complete, :if => :complete

  def complete
    self.status == 'complete'
  end

  def all_components_complete
    self.inspection_components.each do |component|
      # as soon as you find an incomplete component, this inspection
      # is INVALID!
      Errors.add("field","msg") if component.status != 'complete'
    end
  end
end

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection
end


You want to use validates_associated.

probably something like:

validates_associated :inspection_components

Do a search on it and look up the api. There are some useful options for this method as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜