我有兩個模型,問題和答案。在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
我怎樣才能最好的查詢問題基於用戶的答案?