【发布时间】:2015-05-14 18:38:44
【问题描述】:
我无法让嵌套表单在 rails 4.2.0 和 ruby 2.2.0 中工作。我回去尝试关注the Railscast from 2010,但即使按照那个例子,我的子字段也没有出现。我究竟做错了什么?嵌套表单现在有新的最佳实践吗?
意见/调查/_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
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
我猜这很简单,但我现在花了太多时间试图弄明白。有谁知道为什么我的字段没有显示?
解决方案:
我忘记渲染子字段(
<%= f.fields_for :questions do |builder| %>
<div class="field">
<%= builder.label :content, 'Question' %><br>
<%= builder.text_area :content, rows: 3 %>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 ruby-2.2