4
class Parent
  has_one :child
  accepts_nested_attributes_for :child
end
class Child
  belongs_to :parent
end

Using a nested object form, I need to add some extra validations to the child model. These are not always run on Child, so I cannot put them in a validate method in Child. It seems sensible to do the checking in a validate method in Parent, but I'm having trouble adding error messages correctly.

This does work:

class Parent
...
def validate
  errors[ :"child.fieldname" ] = "Don't be blank!"
end

But we lose nice things like I18n and CSS highlighting on the error field.

This doesn't work:

def validate
  errors.add :"child.fieldname", :blank
end
3
  • My initial thinking is to always have the child validations on the child model. Why not do that? Commented Mar 17, 2011 at 18:45
  • Different validations for different situations. In my particular case, some child models are created without a parent, and those have looser validations than those created through parents. Commented Mar 17, 2011 at 18:58
  • 8
    So make them conditional on the presence of a parent. You should still keep them in the child model. Commented Mar 17, 2011 at 19:45

1 Answer 1

1

You should keep them in the child model since that's the one validated, however, you can set conditionals with if: and unless:

class Order < ActiveRecord::Base
  validates :card_number, presence: true, if: :paid_with_card?

  def paid_with_card?
    payment_type == "card"
  end
end

You can do several variations on this, read more in the rails documentation http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation

I guess you could add an attribute, created_by to child, and make Child select which validations to use depending on that one. You can do that like they do in this answer: Rails how to set a temporary variable that's not a database field

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.