2

I'm trying to create a parent object with the set of nested child objects associated to it, however I'm not sure how to access the parent object (other children) in validation methods of the child object before either object is persisted. Here is my scenario in a nutshell:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
  validate :siblings_validation

  def siblings_validation
    siblings = parent.children #parent is Nil here on create (but not on update)
    # compare stuff...
  end
end

The association is created with the standard set of nested forms, something like that:

- form_for @parent do |f|
  = f.text_field :name
  - f.fields_for :children do |c|
    = render :partial => "child_fields", :locals => {:f => c}

Is there a way to access a parent from siblings_validation method of the child object?

Thanks for any responses.

3 Answers 3

3

Untill parent model is saved you have no access to it. I had the same problem, when I had to validate nested models. But you able to access child models from parent. So try to validate through parent model. Or you can create some attr_accessible and use it in child models for validation purposes.

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

2 Comments

I'll give it a go. It's kind of disappointing that there's not reference to the parent whatsoever... :((
Well this seems to be the way. After giving it some thought it not to bad to run such validations on the parent model. Thanks a lot!
0

If you use an explicit .build in your controller you can create a child object which is instantiated, but not saved yet:

def new
  @parent = Parent.new
  @parent.children.build
end

The instantiated object should be able to refer to it's parent and detect its siblings, although it won't end up in the list of .children for the @parent object until after it is saved.

2 Comments

That's exactly what I'm doing (2.times {@parentchildren.build}), however in the validation of the Child model I can't access self.parent. :(
Yeah, didn't see that neither object was persisted, thought the parent existed, but you were creating children. Given that, I agree with bor1s.
0

What exactly are you trying to validate?

Could you not keep the validations for the Parent model in its own class and use validates_associated :parent in Child?

1 Comment

I'm trying to validate whether the child is valid based on comparing attributes to other children of the same parent. So validates_associated probably won't cut it.

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.