我刚开始在rails上学习ruby,我正在使用这段代码来获取问题模型的json表示
post "api/quizzes/addquestion/#{@quiz.id}",
{ question:
{ text: "Question Text Example", mark: 2, choices:["a","b","c","d"], right_answer: "a" }
}.to_json
我得到了: 选择:[],空数组 我不知道其原因,因为所有其他属性都是成功发送的。这个问题的解决方案是什么
我在测试以下方法时使用它:
def add_question
question = Question.new(question_params)
quiz = Quiz.find(params[:quiz_id])
if question.save
quiz.questions << question
render json: { success: true, data:{:question => question}, info:{} }, status: 201
else
render json: { success: false, data:{}, :info => question.errors }, status: 422
end
end
def question_params
params.require(:question).permit(:text, :mark, :choice, :right_answer)
end
测试:
class AddingQuestionsTest < ActionDispatch::IntegrationTest
setup {@quiz = Quiz.create(name: 'Quiz1', subject: 'physics', duration: 10, no_of_MCQ: 5, no_of_rearrangeQ: 5)}
setup {@question = Question.create(text: "Question Text Example", mark: 2, choices:["a","b","c","d"], right_answer: "a")}
test 'successes to add question to a quiz' do
post "api/quizzes/addquestion/#{@quiz.id}",
{ question:
{ text: "Question Text Example", mark: 2, choices:["a","b","c","d"], right_answer: "a" }
}.to_json,
{ 'Accept' => Mime::JSON, 'Content-Type' => Mime::JSON.to_s }
question_response = json(response.body)
assert_equal 201, response.status
assert_equal @quiz.questions.first, @question
assert_equal publish_response[:success], true
end
end
这是问题模型: class Question&lt;的ActiveRecord :: Base的 serialize:choices,Array belongs_to:测验 结束 当我运行测试时,我失败了:assert_equal @ quiz.questions.first,@ items 选择:[] 选择:[“a”,“b”,“c”,“d”]
答案 0 :(得分:0)
我们需要改变
def question_params
params.require(:question).permit(:text, :mark, :choice, :right_answer)
end
to
def question_params
params.require(:question).permit(:text, :mark, :right_answer, :choice => [])
end