2012-05-03 54 views
0

我有2個模型,響應和問題。一個問題has_many的反應,因此每個響應都與一個question_id相關聯。我想查詢與對象@responses中的響應相對應的問題,但我不確定語法。Rails ActiveRecord查詢 - 來自實例變量的數組

@reponses = Response.find([1, 10]) 
@questions = Question.where(:id => [???]) 

我最初的想法是這樣的事情,但這個語法是錯誤的:

@reponses = Response.find([1, 10]) 
@questions = Question.where(:id => @responses.question_id) 

回答

3

你是非常接近嘗試這種

@questions = Question.where(:id => @responses.map(&:question_id)) 

,但我認爲你應該使用在你的響應模式中的範圍

+1

你也可以嘗試這是相同的,但更清潔@questions = Question.where(:id => @ responses.pluck(:ques tion_id)) – Amar

+0

我不確定哪個版本的rails @ diasks2正在使用 – Suborx