2015-12-02 47 views
0

我有兩個模型,問題和答案。在Rails中使用數組查詢模型

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 

我怎樣才能最好的查詢問題基於用戶的答案?

回答

1

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

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) 
1

你可以從不同的角度探討這一問題。你可以有一個自定義的範圍,您Question型號:

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

然後在您的User型號:

def answered_questions 
    Question.by_answerer(id) 
end