Rails:fields_for无效

时间:2015-11-09 07:45:34

标签: ruby-on-rails nested-attributes

我关注RailsCast关于Nested Model Form,但有些事似乎很奇怪。

以下是Model关系

class Question < ActiveRecord::Base
  belongs_to :survey
end

class Survey < ActiveRecord::Base
    has_many :questions
    accepts_nested_attributes_for :questions
end

_form.html.erb (由scaffold创建)

<div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %> 
  </div>
   <% f.fields_for :questions do |builder| %>
    <div class ='question'>
      <%= builder.label :content, "Question" %>
      <br>
      <%= builder.text_area :content, :rows => 3 %> 
    </div>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

survey_controller.rb

# GET /surveys/new
  def new
    @survey = Survey.new

    3.times do |i|
      @survey.questions.build
    end
  end

我原以为它会显示为

enter image description here

然而,它没有显示3个问题块。

1 个答案:

答案 0 :(得分:5)

您错过了表单中非常小但非常重要的部分 - 实际上输出 f.fields_for来电。

您需要致电<%= f.fields_for :question(请注意=)以实际输出生成的表单。