在Rails中使用数组查询模型

时间:2015-12-02 08:21:25

标签: ruby-on-rails-4

我有两个模型,问答。

class Answer < ActiveRecord::Base
  belongs_to :question
end

class Question < ActiveRecord::Base
  has_many :answers
end

在我的控制器操作中,我想要做的是确定用户已回答的所有问题。我有一个查询,可以找到用户的所有答案:

@answers = current_user.answers

现在,我想找出与之相关的问题。我试过了

@questions = Question.where("id in ?", @answers)

但它不起作用。我收到这个错误:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '4,5,6)' at line 1: SELECT `questions`.* FROM `questions` WHERE (id in 4,5,6)

当我尝试这个时:

@questions = Question.where("id in ?", @answers.question_id)

我收到此错误(question_id是答案中的字段):

undefined method `question_id' for [4, 5, 6]:Array

如何根据用户的答案最好地查询问题?

3 个答案:

答案 0 :(得分:1)

Question.where(id: @answers.map(&:question_id))

答案 1 :(得分:1)

您可以从不同的角度处理问题。您可以在Question模型中拥有自定义范围:

scope :by_answerer, -> (user_id) { includes(:answers).where(answers: {user_id: user_id}) }

然后在你的User模型中:

def answered_questions
  Question.by_answerer(id)
end

答案 2 :(得分:0)

线索在生成的SQL中(在错误消息中)

SELECT `questions`.* FROM `questions` WHERE (id in 4,5,6)

这不是有效的语法。你想要

SELECT `questions`.* FROM `questions` WHERE (id in (4,5,6))

所以你正在寻找

@questions = Question.where("id in (?)", @answers)