Ruby-on-rails Rails 4:fields_for 中的 fields_for

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20182019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:04:09  来源:igfitidea点击:

Rails 4: fields_for in fields_for

ruby-on-railsruby-on-rails-4form-forfields-fornested-form-for

提问by user3029400

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:

我正在学习 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

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

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

但祖父的名字行不通。我找不到错误(S)...任何人都可以帮助解决这个问题?谢谢!

回答by cschroed

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