我正在使用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