Rails 4: fields_for in fields_for

╄→гoц情女王★ 提交于 2019-12-04 08:07:43

问题


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
    father=@child.build_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:


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]])


来源:https://stackoverflow.com/questions/20182019/rails-4-fields-for-in-fields-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!