我有一个调查控制器,它会将questions
,answers
和user
收集到UserSurveyAnswer
模式中。
我正在尝试扩展它以允许文本答案(如果需要)。目前,您可以勾选任意数量的答案,但我很难将其扩展为允许文本答案(:text_answer
)
目前,我正在从我的控制器指向此功能
user_survey_answer.rb
def self.update_answer(user_param, user_id)
begin
user_param[:survey].each do |survey|
survey_id = survey[:id]
survey[:question].each do |qs|
question_id = qs[:id]
answer_ids = qs[:answer_ids]
answer_ids.collect{|answer_id| self.create({:user_id => user_id, :survey_id =>survey_id, :question_id => question_id, :answer_id => answer_id}) }
#new bit, which doesn't work
qs[:answer].each do |text_answer|
self.create({:user_id => user_id, :survey_id =>survey_id, :question_id => question_id, :answer_id => text_answer[:id], :text_answer => text_answer[:text_answer]})
end
#end new bit
end
end
return true
rescue Exception => exc
return false
end
end
以下是服务器如何显示通过的信息。
"user"=>{"survey"=>[
{"id"=>"1", "question"=>[
{"id"=>"1", "answer_ids"=>["1"]}
]
},
{"id"=>"2", "question"=>[
{"id"=>"2", "answer"=>[
{"id"=>"2", "text_answer"=>"dwqdw"}
]
}
]}
]}
关于如何将上述信息(特别是第二部分)保存到我的UserSurveyAnswer
模态中的任何想法?
编辑:完整的UserSurveyAnswer模式
class UserSurveyAnswer < ActiveRecord::Base
validates_uniqueness_of :user_id, :scope => [:survey_id, :question_id, :answer_id]
belongs_to :user
belongs_to :survey
belongs_to :question
belongs_to :answer
def self.update_answer(user_param, user_id)
begin
user_param[:survey].each do |survey|
survey_id = survey[:id]
survey[:question].each do |qs|
question_id = qs[:id]
answer_ids = qs[:answer_ids]
answer_ids.collect{|answer_id| self.create({:user_id => user_id, :survey_id =>survey_id, :question_id => question_id, :answer_id => answer_id}) }
text_answer = qs[:answer]
UserSurveyAnswer.create(user_id: user_id, survey_id: survey_id, question_id: question_id, answer_id: text_answer[:id], text_answer: text_answer[:text_answer])
end
end
return true
rescue Exception => exc
return false
end
end
end
答案 0 :(得分:0)
首先,我会使用嵌套属性,因此所有这些都会自动保存,而不是您手动完成所有这些操作。但是,我不确定行self.create
是否有意义。我以前从未真正从模型中创建过对象。如果我理解你的关联,你应该把:
UserSurveyAnswer.create(user_id: user_id, survey_id: survey_id, question_id: question_id, answer_id: text_answer[:id], text_answer: text_answer[:text_answer])
编辑:所以我也要将它之前的行更改为:
answer_ids.collect{|answer_id| UserSurveyAnswer.create(user_id: user_id, survey_id: survey_id, question_id: question_id, answer_id: answer_id) }
答案 1 :(得分:0)
我把它从模态中删除并意识到当存在文本问题时,answer_ids不会,因此该函数在第一个保存行上失败:
answer_ids.collect{|answer_id| self.create({:user_id => user_id, :survey_id =>survey_id, :question_id => question_id, :answer_id => answer_id}) }
一旦我为此进行了异常处理(以及第二次保存的后续处理),一切都有效!
感谢@ryan k的帮助