在我的应用中,survey
和question
之间存在has_many:through关系:
class Survey < ActiveRecord::Base
has_many :answers, dependent: :destroy
has_many :questions, through: :answers
end
class Question < ActiveRecord::Base
has_many :answers, dependent: :destroy
has_many :surveys, through: :answers
end
class Answer < ActiveRecord::Base
belongs_to :survey
belongs_to :question
end
我有一个表单可以添加一个包含question
复选框的新调查表:
= form_for @survey, html: { class: "form-horizontal"} do |f|
= render "layouts/messages", target: @survey
.form-group
= f.label I18n.t('.survey.form.name')
= f.text_field :name, class: "form-control"
.form-group
= f.label I18n.t('.survey.form.questions')
%ul
= hidden_field_tag "survey[question_ids][]", nil
- @questions.each do |question|
%li.checkbox
= check_box_tag "survey[question_ids][]", question.id, @survey.question_ids.include?(question.id)
= question.intro
.form-group
.controls
= f.submit(class: 'btn btn-default', value: I18n.t('.general.form.save'))
survey
控制器create
操作如下所示:
def create
@survey = Survey.new(survey_params)
if @survey.save
redirect_to surveys_path, notice: I18n.t('.survey.messages.created')
else
render action: "new"
end
end
private
def survey_params
params.require(:survey).permit(:name, :question_ids => [])
end
当我填写表单并提交时,它将无法保存,我只在服务器日志中看到回滚:
Started POST "/surveys" for ::1 at 2015-05-24 12:29:00 +0200
Processing by SurveysController#create as HTML
Parameters: {"utf8"=>"✓", "survey"=>{"name"=>"fdfdfd", "question_ids"=>["", "1", "2"]}, "commit"=>"Opslaan"}
(0.3ms) BEGIN
(0.2ms) ROLLBACK
那我在这里做错了什么?
答案 0 :(得分:0)
尝试
@survey = Survey.build(survey_params)
SurveysController
中的。
答案 1 :(得分:0)
似乎这是验证错误。尝试将save
临时替换为save!
。它应该导致异常,它使您能够调查问题的更多细节。