Reputation: 55263
This is what I have:
post.rb:
class Post < ActiveRecord::Base
has_many :replies, :dependent => :destroy
accepts_nested_attributes_for :replies, :allow_destroy => true
end
reply.rb:
class Reply < ActiveRecord::Base
belongs_to :post
end
posts/_reply_fields.html.erb:
<p>
<%= f.label :content, "Reply" %><br />
<%= f.text_area :content, :rows => 3 %><br />
</p>
posts/_form.html.erb:
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.label :user %><br>
<%= f.text_field :user %>
</div>
<div class="replies">
<% f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
schema.rb:
create_table "posts", force: true do |t|
t.string "content"
t.string "user"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "replies", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
end
The output in the replies parts is just:
<div class="replies">
</div>
The reply fields are not showing up at all. What could be the problem?
Upvotes: 0
Views: 66
Reputation: 76774
Further to the comment & answer, you also need to build
the replies
ActiveRecord objects:
#app/controllers/posts_controller.rb
def new
@post = Post.new
@post.replies.build
end
Upvotes: 1
Reputation: 3709
<div class="replies">
<%= f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>
Upvotes: 1