3

These are my models:

class Parent < ActiveRecord::Base
    has_one :child, :dependent => :destroy
end

class Child < ActiveRecord::Base
    belongs_to :parent
    accepts_nested_attributes_for :parent
end

My goal is update 1 parent attribute (email) when I'm creating the child (it means the end user is on the child form where the controller action is "new")

Hay que tener en cuenta que simpre cuando quiera crear el child, existe ya antes de antes un parent en la db.

My child controller:

def new
    @child = Child.new
    @child.parent = current_parent
end 


def create
    @child = Child.new(params[:child])
    @child.parent = current_parent


    respond_to do |format|
        if @child.save
        #.....
        else
            format.html { render :action => "new" }
        end
    end
end

Child form:

<% form_for @child, :html => {:multipart => true} do |f| %>
......
<% f.fields_for :parent do |p| %>
    <%= p.label :email, t(:label_child_email), :req => true %>
    <%= p.text_field :email, :class => "field" %>
<% end %>

<%end%>

When the users clicks on Save button they get:

Couldn't find Parent with ID=4147 for Child with ID=

And the parameters:

{"commit"=>"Save",
     "child"=>{
         ...........
         "parent_attributes"=>{"email"=>"[email protected]", "id"=>"4147"
     },
         ..........
}

Do you know what's wrong ?

Thanks !

1 Answer 1

0

The way you are building the child is causing the problem. Try the following

def new
    @child = current_parent.build_child
end 

def create
    @child = current_parent.build_child(params[:child])
    // more code
end

Check out build_association and create_association here

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

4 Comments

On new action, I'm getting undefined method `build' for nil:NilClass
Thanks for you reply ! Now there is not errors on new action, but when I try to save (create action) I get this: Couldn't find Parent with ID=4148 for Child with ID= It seems first I have to create the Child and then update the Parent...
Not sure why you are getting that error. Check if the parent object with that ID exists in the database. Also checkout the following link. guides.rubyonrails.org/…
@ratamaster did you ever get it to save correctly? I'm getting the same error and am not sure if you can update the parent through the child using nested_attribute.

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.