Rails 4:fields_for中的fields_for [英] Rails 4: fields_for in fields_for

查看:85
本文介绍了Rails 4:fields_for中的fields_for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习RoR,并且我试图找到如何在具有has_one模型的另一个模型中设置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

我在Railscasts上使用了嵌套模型表单第1部分来获取这些信息: 在children_controller.rb中:

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

我的表单:

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

推荐答案

尝试切换:

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

这篇关于Rails 4:fields_for中的fields_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆