【问题标题】:Why is my nested form not showing up at all?为什么我的嵌套表单根本不显示?
【发布时间】:2014-02-10 13:38:24
【问题描述】:

这就是我所拥有的:

post.rb:

class Post < ActiveRecord::Base
  has_many :replies, :dependent => :destroy
  accepts_nested_attributes_for :replies, :allow_destroy => true
end

回复.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

回复部分中的输出只是:

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

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

【问题讨论】:

  • 我想你可能漏掉了一个等号:&lt;%= f.fields_for...

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


【解决方案1】:
  <div class="replies">
    <%= f.fields_for :replies do |builder| %>
      <%= render 'reply_fields', :f => builder %>
    <% end %>
  </div>

【讨论】:

    【解决方案2】:

    除了评论和回答,还需要buildrepliesActiveRecord 对象:

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

    【讨论】:

    • 谢谢,但很奇怪,每次我编辑帖子时都会添加一个新回复。即使回复控制器中的编辑操作为空。
    • 你是在使用继承的资源还是类似的东西?
    • @Rick Peck 在 routes.rb 中?不,它们只是一个接一个地列出来。
    • 您评论说,尽管您在编辑操作中没有任何代码,但您在编辑帖子时会显示您的表单——我想知道这是否是因为您使用的是 inherited_resources(会否定编辑阳离子中对代码的需要)?
    • 好吧,不,我的代码中没有任何 inherited_resources 字样。
    猜你喜欢
    • 2021-05-03
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2016-09-13
    相关资源
    最近更新 更多