2013-11-27 79 views
1

我有一個'問題'模型。ActiveRecord和複雜的查詢

class Question < ActiveRecord::Base 
    has_many :answers 
end 

...和答案模型...

class Answer < ActiveRecord::Base 
    belongs_to :question 
    has_many :answer_points 
end 

...和答案要點模型...

class AnswerPoint < ActiveRecord::Base 
    attr_accessible :points 
    belongs_to :answer 
    belongs_to :attribute 
end 

...和用戶應答模型...

class UserAnswer < ActiveRecord::Base 
    belongs_to :answer 
    belongs_to :user 
end 

...和屬性模型。

class Attribute < ActiveRecord::Base 
    has_many :answer_points 
end 

用戶回答問題,並且每個答案可以具有與特定屬性相關聯的點值。 (即這個答案給出2個通信點,一個分析等)

我想顯示用戶回答問題時生成的前5-10個屬性的列表。我知道如何從原始的SQL角度來解決這個問題,但我更喜歡更優雅的rails-y方法。有什麼建議?

回答

2

嗯,我看中了這個:

questions = Question.where(:arbitrary_field => 'doge') 
answers = Answer.where('question_id in (?)', questions.pluck(:id)) 
AnswerPoint.where('answer_id in (?)', answers.pluck(:id)).select('attribute_id, sum(points) as points').group('attribute_id').order('points desc') 

它返回每個獨特attribute_id的AnswerPoint模型,以及點屬性包含點的總和。適用於我,但我願意提供建議!