Checking models against parent model

I have two models, one of them is the parent, and the parent is accepts_nested_attributes_for and validates_associated.

However, some of my checks have: if necessary to check one of the properties of the parent.

I thought I could do something like this:

validates_presence_of :blah, :if => Proc.new{|thing| thing.parent.some_value.present?} 

However, the parent relationship does not appear during validation (I would suggest that children receive an instance and are checked first.

So is there a way to do what I think? Is it possible?

+4
source share
3 answers

You can use before_update or before_create callbacks to suit your needs.

 def before_update self.errors.add("Error Message") if self.parent.some_value.present? return false if self.errors.count > 0 end def before_create self.errors.add("Error Message") if self.parent.some_value.present? return false if self.errors.count > 0 end 
+1
source

This validation should work:

validates_associated: children

But it will not be

The reason is, as I understand it, because using acceptes_nested_attributes_for creates nested objects directly in the database through a single transaction without passing any child checks.

What you can do here: write your own validation in the parent model and confirm the creation of the child objects.

0
source

Use the :inverse_of parameter to associate with the parent, so children will have a link to the parent when they are created.

 class Parent < ActiveRecord::Base has_many :children, :inverse_of => :parent accepts_nested_attributes_for :children end class Child < ActiveRecord::Base belongs_to :parent end p = Parent.new :children_attributes => { 0 => { :child_attribute => 'value' } } p.children.first.parent #=> shouldn't be nil anymore 
0
source

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


All Articles