0

我无法让嵌套表单在 rails 4.2.0 和 ruby​​ 2.2.0 中工作。我回去尝试从 2010 开始关注 Railscast,但即使按照那个例子,我的子字段也没有出现。我究竟做错了什么?现在嵌套表单有新的最佳实践吗?

意见/调查/_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 %>

控制器/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

模型/问题.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

模型/调查.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 %>
4

1 回答 1

1

你需要<%=在你的fields_for

<%= f.fields_for :questions do |builder| %>
    <div class="field">
      <%= builder.label :content, 'Question' %><br>
      <%= builder.text_area :content, rows: 3 %>
    </div>
<% end %>
于 2015-03-12T14:39:38.657 回答