我正在尝试在连接表中实现创建具有多对多关系(在调查和问题之间)的记录。我希望用户能够以单一形式创建一个包含问题的调查,但问题不会出现。
[编辑:在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 partial:
<%= 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“问题”,但不会低于此。我怎么能纠正这个?
答案 0 :(得分:1)
在_form
部分内容中,您需要在=
之前添加f.fields_for
,以便在页面上显示。
<%= f.fields_for :questions do |builder| %>
<p>
<%= builder.label :question_text, "Question Text" %><br />
<%= builder.text_field :question_text %>
</p>
<% end %>
此外,您可以将new.html.erb
更新为:
<h1>New Survey</h1>
<%= render :partial => "form" %>
答案 1 :(得分:0)