Rails 4:fields_for中的fields_for

时间:2013-11-24 22:38:10

标签: ruby-on-rails ruby-on-rails-4 form-for fields-for nested-form-for

我正在学习RoR,我正在尝试找到如何使用has_one模型在另一个中设置fields_for:

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

我在Railscasts上使用嵌套模型表单第1部分来获取这些: 在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

我的表格:

<%= 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 %>

我正在尝试使用以下方法检索数据:

<%= child.father.name %>
<%= child.father.grandfather.name %>
但是祖父的名字不起作用。 我找不到错误......有人帮忙吗? 谢谢!

1 个答案:

答案 0 :(得分:20)

尝试切换:

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

到:

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

切换:

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

要:

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