我有一个跟踪has_many
测验和测验has_many
问题。
quiz.rb:
class Quiz < ActiveRecord::Base
belongs_to :track
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions
end
question.rb:
class Question < ActiveRecord::Base
belongs_to :quiz
end
quizzes_controller.rb:
def new
@quiz = Quiz.new
@track = Track.find(params[:permalink])
@course = Course.find(@track.course_id)
3.times { @quiz.questions.build }
end
def create
@track = Track.find(params[:permalink])
@quiz = @track.quizzes.build(quiz_params)
@course = Course.find(@track.course_id)
if @quiz.save
flash[:success] = 'Quiz successfully created'
redirect_to quiz_path @quiz
else
redirect_to track_path @track
end
end
private
def quiz_params
params.require(:quiz).permit(:name, :information, :order,
:permalink, :user_id,
questions_attributes: [:id, :content])
end
提交上的参数:
{"utf8"=>"✓",
"authenticity_token"=>"...",
"quiz"=> {
"name"=>"Test Quiz",
"questions_attributes"=> {
"0"=>{"content"=>"This is question 1?"},
"1"=>{"content"=>"This is question 2?"},
"2"=>{"content"=>""}
}, "user_id"=>"1",
"order"=>"3"
}, "commit"=>"Submit",
"permalink"=>"1-basics"}
当我按提交时,会创建测验,但不会创建问题。
新的参数:
def quiz_params
params.require(:quiz).permit(:name, :information, :order,
:permalink, :user_id,
questions_attributes: [:id, :content, :_destroy, answers_attributes: [:id, :content, :_destroy]] )
end
答案 0 :(得分:1)
我认为问题出在accepts_nested_attributes_for
:
reject_if: proc { |q| q['name'].blank? }
如果content
为空(考虑请求参数),您可能应该拒绝实例:
reject_if: proc { |q| q['content'].blank? }
答案 1 :(得分:0)
问题解决了。嵌套参数需要用大括号括起来:
def quiz_params
params.require(:quiz).permit(:name, :information, :order,
:permalink, :user_id,
{ questions_attributes: [:id, :content] })
end