Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: fields_for in fields_for

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!

like image 983
user3029400 Avatar asked Nov 24 '13 22:11

user3029400


1 Answers

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]])
like image 118
cschroed Avatar answered Nov 11 '22 17:11

cschroed