Custom validation errors on nested models

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

Using the nested form of the object, I need to add some additional checks to the child model. They do not always run on Child, so I cannot put them in the validate method in Child. It seems reasonable to do validation in the verification method in Parent, but I am not able to correctly add error messages.

It works:

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

But we are losing nice things like I18n highlighting and CSS in the error field.

This does not work:

 def validate errors.add :"child.fieldname", :blank end 
+4
source share
1 answer

You must save them in the child model, as one is confirmed, however you can set the conventions using 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 options for this, read more in the rail documentation http://edgeguides.rubyonrails.org/active_record_validations.html#conditional-validation

I think you could add the attribute created_by to the child and make Child select which checks to use depending on this. You can do this, as in this answer: Rails, how to set a temporary variable that is not a database field

+1
source

Source: https://habr.com/ru/post/1344167/


All Articles