fields_for
块不会以has_many
关系输出。这个问题出现在我正在进行的一个有点参与的项目中。我将其分解为一个非常简单的测试用例,但它仍然不起作用。之前已经问过这个问题,通常是问题所在
嵌套对象不存在。但是在这里,嵌套对象似乎确实存在,如代码注释中所述。我对rails非常陌生,所以它可能是显而易见的。
以下是简单的案例模型代码:
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
简单案例控制器:
class ParentController < ApplicationController
def index
@parent = Parent.find_by_id(1)
end
end
简单案例视图:
<%= form_for @parent, {:url=>{:action=>:index}} do |f| %>
<!-- this outputs ok -->
<%= f.text_field :name %>
<% f.object.children.each do |c| %>
<!-- this outputs "child1", so the nested object exists -->
<%= c.name %>
<% f.fields_for c do |field| %>
this line does NOT output, nor does the field below
<%= field.text_field :name %>
<% end %>
<% end %>
<% end %>
我也试过了,看到了同样的结果:
<%= form_for @parent, {:url=>{:action=>:index}} do |f| %>
<%= f.text_field :name %>
output here
<% f.fields_for :children do |field| %>
no output here nor the field below
<%= field.text_field :name %>
<% end %>
<% end %>
我还尝试在控制器中使用新的@parent
对象并@parent.build_child
(已将关联更改为has_one
)。那仍然看到了同样的结果。
答案 0 :(得分:1)
您忘记在=
之后添加<%
符号。
替换:
<% f.fields_for :children do |field| %>
使用:
<%= f.fields_for :children do |field| %>