Rails 4.2.0 中的嵌套模型表单 (accepts_nested_attributes_for):子字段不显示

Nested model forms (accepts_nested_attributes_for) in Rails 4.2.0: subfields not displaying

我无法让嵌套表单在 rails 4.2.0 和 ruby 2.2.0 中工作。我返回并尝试遵循 the Railscast from 2010,但即使遵循该示例,我的子字段也没有出现。我究竟做错了什么?现在有嵌套表单的新最佳实践吗?

views/surveys/_form.html.erb:

<%= form_for(@survey) do |f| %>
    ...
    <% f.fields_for :questions do |builder| %>
        <div class="field">
          <%= builder.label :content, 'Question' %><br>
          <%= builder.text_area :content, rows: 3 %>
        </div>
    <% end %>
    ...
<% end %>

controllers/survey_controller.rb

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]
  ...
  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times { @survey.questions.build }
  end
  ...
  private
    ...
    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, questions_attributes:[:content])
    end
end

models/questions.rb

# == Schema Information
#
# Table name: questions
#
#  id         :integer          not null, primary key
#  survey_id  :integer
#  content    :text
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Question < ActiveRecord::Base
  belongs_to :survey
end

models/surveys.rb

# == Schema Information
#
# Table name: surveys
#
#  id         :integer          not null, primary key
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Survey < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions
end

我猜这很简单,但我现在花了太多时间试图弄明白。有谁知道为什么我的字段没有显示?


解法:

我忘记渲染子字段(<% 而不是 <%=)。 _form.rb 中的正确文本应该是:

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

您的 fields_for

需要 <%=
<%= f.fields_for :questions do |builder| %>
    <div class="field">
      <%= builder.label :content, 'Question' %><br>
      <%= builder.text_area :content, rows: 3 %>
    </div>
<% end %>