【发布时间】:2015-06-17 05:30:27
【问题描述】:
我正在尝试使用连接表中捕获的多对多关系(调查和问题之间)创建记录。我希望用户能够创建一个调查问卷,其中包含一个表单中的问题,但问题不会出现。
[编辑:RAJ修改后,只显示一个问题,不保存到数据库中。]
[编辑:Rails 版本 4.2.0,ruby 版本 2.2.1p85,物有所值]
[编辑:按照RAJ 的建议,在部分表单中添加了“=”]
问题模型:
class Question < ActiveRecord::Base
has_many :survey_questions
has_many :surveys, :through => :survey_questions
end
调查模型:
class Survey < ActiveRecord::Base
has_many :survey_questions
has_many :questions, :through => :survey_questions
accepts_nested_attributes_for :survey_questions
end
SurveyQuestion 连接表:
class SurveyQuestion < ActiveRecord::Base
belongs_to :survey
belongs_to :question
accepts_nested_attributes_for :question
end
/surveys/_form.html.erb 部分:
<%= form_for @survey do |f|%>
<h3>The Survey Itself</h3>
<%= f.label :title %>
<%= f.text_field :title %> <br/>
<h3>Questions:</h3>
<%= f.fields_for :questions do |builder| %>
<p>
<%= builder.label :question_text, "Question Text" %><br />
<%= builder.text_field :question_text %>
</p>
<% end %>
<%= f.submit "Submit" %>
<% end %>
/surveys/new.html.erb 视图:
<h1>New Survey</h1>
<%= render :partial => "form" %>
最后是 SurveysController:
class SurveysController < ApplicationController
# I have a few other actions here, like list, edit, delete and so forth
def new
@survey = Survey.new
3.times do
question = @survey.questions.build
survey_question_combo = @survey.survey_questions.build
end
def create
@survey = Survey.new(params[:survey].permit(:title))
if @survey.save
redirect_to :action => "show", :id => @survey
else
render :action => "new"
end
end
end
问题是,当我创建一个新的调查时,HTML 最多显示 h3“问题”,但没有低于它。我该如何纠正这个问题?
【问题讨论】:
标签: ruby-on-rails model nested-forms jointable