Ian Greenleaf Young
Ian Greenleaf Young

Reputation: 1958

Custom validation errors on nested models

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

Upvotes: 4

Views: 2142

Answers (1)

Alexander Kuzmin
Alexander Kuzmin

Reputation: 1120

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

Upvotes: 1

Related Questions