16

I am learning RoR and i am trying to find how to set a fields_for in another one with has_one models like this:

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

class Father < ActiveRecord::Base
    has_one :child
    belongs_to :grandfather
    accepts_nested_attributes_for :grandfather
end


class Grandfather < ActiveRecord::Base
    has_one :father
end

I used Nested Model Form Part 1 on Railscasts to get these: In children_controller.rb:

  def new
    @child = Child.new
    [email protected]_father
    father.build_grandfather
  end

def child_params
      params.require(:child).permit(:name, father_attributes:[:name], grandfather_attributes:[:name])
    end

And my form:

<%= form_for(@child) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  mother:<br>
  <%= f.fields_for :father do |ff| %>
    <%= ff.label :name %>
    <%= ff.text_field :name %><br>
      grand mother:<br>
      <%= f.fields_for :grandfather do |fff| %>
        <%= fff.label :name %>
        <%= fff.text_field :name %>
      <% end %>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I am trying to retrieve the datas with:

<%= child.father.name %>
<%= child.father.grandfather.name %>

but the grandfather's name won't work. I cannot find the mistake(s)...anyone to help on this? Thanks!

1 Answer 1

24

Try switching:

<%= f.fields_for :grandfather do |fff| %>

to:

<%= ff.fields_for :grandfather do |fff| %>

And switching:

params.require(:child).permit(:name, father_attributes:[:name], grandfather_attributes:[:name])

To:

params.require(:child).permit(:name, father_attributes:[:name, grandfather_attributes:[:name]])
Sign up to request clarification or add additional context in comments.

Comments

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.