gpt4 book ai didi

ruby-on-rails - rails 4 : fields_for in fields_for

转载 作者:行者123 更新时间:2023-12-03 20:25:25 26 4
gpt4 key购买 nike

我正在学习 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 上使用 Nested Model Form Part 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 %>

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

最佳答案

尝试切换:

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

关于ruby-on-rails - rails 4 : fields_for in fields_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20182019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com