我正在使用ActiveRecord的rails项目。我正在做一些循序渐进的查询,由于我是Activerecord的新手,似乎缺少关键概念。我无法在模型上获得标识,因此无法执行查询。这里是我的代码:无法获得RoR Active记录模型ID来执行查询
questions = JSON.parse(q)
selected_answers = questions.map do |ques|
ques['options'].map do |opt|
Answer.where(value: opt['title'])
end
end
participants = selected_answers.flatten!.map do |sa|
Participant.where(answers: sa.id)
end
stats[:answers] = participants.map do |p|
Answer.where(participants: p.id) #this line causes an error
end
我得到错误
NoMethodError (undefined method `id' for #<Participant::ActiveRecord_Relation:0x007fc478423bc0>):
app/services/survey_statistics.rb:143:in `block in get_question'
app/services/survey_statistics.rb:142:in `map'
app/services/survey_statistics.rb:142:in `get_question'
app/services/survey_statistics.rb:25:in `block in questions'
app/services/survey_statistics.rb:22:in `questions'
app/controllers/api/v1/reports_controller.rb:13:in `questions'
它看起来像你的变量'参与者'是一个集合的集合。此链接可能会帮助您:http://stackoverflow.com/questions/27021036/undefined-method-id-for-activerecordrelation – Pholochtairze