Reputation: 3221
I have a Track that has_many
Quizzes and a Quiz has_many
Questions.
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
params on submit:
{"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"}
When I press submit the quiz is created but the questions are not created.
New params:
def quiz_params
params.require(:quiz).permit(:name, :information, :order,
:permalink, :user_id,
questions_attributes: [:id, :content, :_destroy, answers_attributes: [:id, :content, :_destroy]] )
end
Upvotes: 0
Views: 820
Reputation: 3221
Problem solved. The nested parameters need to be wrapped in curly brackets:
def quiz_params
params.require(:quiz).permit(:name, :information, :order,
:permalink, :user_id,
{ questions_attributes: [:id, :content] })
end
Upvotes: 0
Reputation: 7043
I think the problem is on accepts_nested_attributes_for
:
reject_if: proc { |q| q['name'].blank? }
You probably should reject instances if content
is blank (considering request parameters):
reject_if: proc { |q| q['content'].blank? }
Upvotes: 1