Ruby on Rails嵌套属性字段未显示

时间:2016-06-03 21:53:02

标签: ruby-on-rails ruby forms

我在使用嵌套属性的调查构建器上关注Ryan Bates旧教程。我已经按照正确的方式进行了操作,但出于某种原因,嵌套的字段不会显示在新操作中。

Controller:surveycreate.rb

...
    def new
        @surveycreate = Surveycreate.new
        3.times { @surveycreate.questions.build } 
      end
...

模型:surveycreate.rb

class Surveycreate < ActiveRecord::Base
    has_many :questions, :dependent => :destroy
    accepts_nested_attributes_for :questions
end

question.rb

class Question < ActiveRecord::Base
    belongs_to :surveycreate
end

查看:surveycreates / _form.html.erb

<%= form_for(@surveycreate) do |f| %>
  <% if @surveycreate.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@surveycreate.errors.count, "error") %> prohibited this surveycreate from being saved:</h2>

      <ul>
      <% @surveycreate.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.label :name %><br>
  <%= f.text_field :name %>

  <% f.fields_for :questions do |builder| %>
  <p>
    <%= builder.label :content, "Question" %><br />
    <%= builder.text_area :content, :rows => 3 %>
  </p>
  <% end %>


  <div class="actions">
    <%= f.submit :Create %>
  </div>
<% end %>

模式

create_table "questions", force: :cascade do |t|
    t.integer  "surveycreate_id"
    t.text     "content"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "surveycreates", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

我使用rails 4.2.1和Ruby 2.0。我知道这一集已经足够老了所以也许这里发生了一些变化,或者我做错了什么。任何指导?感谢。

1 个答案:

答案 0 :(得分:1)

您在=的行上忘记了f.fields_for。 Rails将汇总将在fields_for块中生成的所有内容,您应该输出它。

  <%= f.fields_for :questions do |builder| %>
    <p>
      <%= builder.label :content, "Question" %><br />
      <%= builder.text_area :content, :rows => 3 %>
    </p>
  <% end %>