2014-01-29 14 views
1

我有一个名为User模型,它具有自加入协会,因为这:查找最热门从父打进及其所有儿童的Rails

has_many :children, class_name: "User", 
    foreign_key: "parent_id" 
belongs_to :parent, class_name: "User" 

,它也有一个Post模型的关联:

User has_many post 

每个帖子对象都有一个评分属性,我试图找到给定用户和他们的孩子得分最高,哪个得分大于0,哪些满足特定属性的帖子。所以现在,我有这个方法在我的岗位模型:

def self.top_related_scored_by_user_id(user_id, max) 
    where(:user_id => user_id). 
     where(:related_image => true). 
     where('score > 0'). 
     order(score: :desc). 
     first(max) 
    end 

但是,我想应该能看不只是与user_ID的用户,同时也为自己的孩子。我怎样才能做到这一点?

感谢

回答

1

它非常简单:

def self.top_related_scored_by_user_id(user_ids, max = nil) 
    user_ids = user_ids.kind_of?(Array) ? user_ids : [user_ids] 
    scope = where(:user_id => user_ids) 
    scope = scope.where(:related_image => true) 
    scope = scope.where('score > 0') 
    scope = scope.order(score: :desc) 
    scope = scope.limit(max) if max.present? 
    scope 
end 

你可以给一个ID阵列where子句,就会产生这样的情况:

WHERE id IN (1, 2, 3, 4) 

你的方法有点改进,使它更灵活e:

def self.top_related_scored_by_user_id(user_ids, options = {}) 
    options = { limit: 10, order: 'score DESC', 
       score: 0, related_image: true }.merge(options) 
    user_ids = user_ids.kind_of?(Array) ? user_ids : [user_ids] 

    scope = where(:user_id => user_ids) 
    scope = scope.where(:related_image => options[:related_image]) 
    scope = scope.where('score > ?', options[:score]) 
    scope = scope.order(options[:order]) 
    scope = scope.limit(options[:limit]) 
    scope 
end 

这样,您可以使用相同的功能轻松设置选项,并且它具有可根据需要覆盖的默认值。

+0

噢好吧。所以我需要在使用该方法之前弄清楚id(父母和孩子),对吧? –

+0

是的,您需要在使用此方法之前检索这些ID。 – MrYoshiji

+0

如果ids数组可能很大,则可能需要使用子查询将工作转移到数据库。 – jessecurry