Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent when using accepts_nested_attributes_for

When receiving:

{
   parent:{
      children_attributes:[
        {child1}, {child2}
      ]
   }
}

And child1 instance is about to be created, I don't have parent_id set. I suppose this is set in save time.

How can I handle this to say something like:

class Child < ActiveRecord::Base
  belongs_to :parent
  before_save :do_something

  def do_something
    # access parent here
    # I can't, since parent_id is nil yet
  end
end

 Update to be more clear

class Parent <  ActiveRecord::Base
  has_many :children
  accepts_nested_attributes_for :children
end

Update 2

I tried this from related questions:

class Parent <  ActiveRecord::Base
  has_many :children, inverse_of: :parent
end

But same issue.

Update 3 according comment

I tried this

class Parent
  before_save :save_children
  attr_accessor :children_attributes

  def save_children
    children_attributes.all? do |k, attrs|
      # tried different things here, this one is the one I expected to work the most 
      child = Child.new attrs.merge(parent_id: id)
      child.save
    end
  end

I added parent_id to child attr_accessible call.

What am I missing?

like image 423
sites Avatar asked May 20 '26 06:05

sites


1 Answers

The cause of this problem for me was the validation of the presence of the parent in the child class.

I essentially removed this line from the Child object and it works.

validates :parent, presence: true

From what I've found, however, the correct way to resolve this is the use of the inverse_of parameter. If you add this to the has_many of the parent and the belongs_to of the child, you should be good to go.

In the parent:

has_many :child, inverse_of: :parent

In the child:

belongs_to :parent, inverse_of: :child
like image 159
Eric B Avatar answered May 22 '26 23:05

Eric B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!