我有一个名为User的模型,它具有自加入关联,如下所示:
has_many :children, class_name: "User",
foreign_key: "parent_id"
belongs_to :parent, class_name: "User"
它还与Post模型有关联:
User has_many post
每个Post对象都有一个得分属性,我试图找到给定用户及其孩子的帖子,这些用户得分最高,得分大于0,并且满足特定属性。所以现在,我在Post模型中有这个方法:
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的用户,还可以查看他们的孩子。我怎么能这样做?
由于
答案 0 :(得分: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
你可以给where子句赋一个id数组,它会产生这样的条件:
WHERE id IN (1, 2, 3, 4)
您的方法有点改进,以使其更灵活:
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
通过这种方式,您可以轻松地使用相同的功能设置选项,并且它具有可以在需要时覆盖的默认值。