The fields_for block doesn’t output in a has_many relationship. This problem came up in a somewhat involved project I was working on. I broke it down to a very simple test case, but it still doesn’t work. This question has been asked before and the problem was usually
that the nested object didn’t exist. But here, the nested object does appear to exist, as explained in the code comments. I’m pretty new to rails so it could be something obvious.
Here is the simple case model code:
class Parent < ActiveRecord::Base
has_many :children
accepts_nested_attributes_for :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
Simple case controller:
class ParentController < ApplicationController
def index
@parent = Parent.find_by_id(1)
end
end
Simple case view:
<%= 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 %>
I also tried this and saw the same result:
<%= 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 %>
I also tried with a new @parent object in the controller and a @parent.build_child
(having changed the assoc to a has_one). That still saw the same result.
You’ve forgotten to put the
=sign after<%.Replace:
with: