为什么我的嵌套表单根本没有出现?

时间:2014-02-10 13:38:25

标签: ruby-on-rails forms ruby-on-rails-4 nested-forms

这就是我所拥有的:

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

帖/ _reply_fields.html.erb:

<p>
  <%= f.label :content, "Reply" %><br />
  <%= f.text_area :content, :rows => 3 %><br />
</p>

帖/ _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

回复部分中的输出只是:

<div class="replies">
  </div>

回复字段根本没有显示。可能是什么问题?

2 个答案:

答案 0 :(得分:1)

  <div class="replies">
    <%= f.fields_for :replies do |builder| %>
      <%= render 'reply_fields', :f => builder %>
    <% end %>
  </div>

答案 1 :(得分:1)

继续评论&amp;回答,您还需要build replies ActiveRecord对象:

#app/controllers/posts_controller.rb
def new
    @post = Post.new
    @post.replies.build 
end