【发布时间】:2016-05-13 22:10:47
【问题描述】:
我正在使用 ActiveRecord 开发 Rails 项目。我正在做一些逐步的查询,似乎我缺少关键概念,因为我是 Activerecord 的新手。我无法在模型上获取 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'
【问题讨论】:
-
看起来您的变量“参与者”是集合的集合。此链接可能对您有所帮助:stackoverflow.com/questions/27021036/…
标签: ruby-on-rails ruby database activerecord orm