出于摘要邮件程序的目的,我想获得用户可以查看我的应用程序的答案。
用户应该只看到他已经订阅的所有组中投票最高的 5 个答案。
协会:
Answer
# Returns 5 the most voted answers
#
scope :best, order("votes_count DESC")
belongs_to :user
belongs_to :group
User
belongs_to :group
has_many :answers, :dependent => :destroy
has_many :groups, through: :subscriptions
Group
has_many :subscriptions
has_many :users, through: :subscriptions
has_many :questions
has_many :answers
所以我正在寻找如何做到这一点的最佳方法:
class BestAnswers
def self.for_user(user)
answers = []
user.groups.each |group|
answers << group.answers
end
return answers
end
end
经典方法是:
class BestAnswers
def self.for_user(user)
Answer.where(:group_id => user.groups).best.limit(5)
end
end
但是,AFAIK 自 Rails 3.1 has_many
起支持链接。你能测试一下并报告吗?
#User model: has_many :group_answers, :through => :groups
user.group_answers.best.limit(5)
对我来说,
这段代码似乎属于用户模型而不是一个新类。
# app/models/user.rb
class User < ActiveRecord::Base
# Return the five best answers for a user
def best_answers
groups.each_with_object([]) do |group, array|
array << group.answers.best.limit(5)
end
end
end
对于您更新的规格,tokland的答案看起来是一个非常好的方法。