Sql 在Rails中查找家长及其所有子女的最高分数
我有一个名为User的模型,它具有如下自加入关联:Sql 在Rails中查找家长及其所有子女的最高分数,sql,ruby-on-rails,model,Sql,Ruby On Rails,Model,我有一个名为User的模型,它具有如下自加入关联: has_many :children, class_name: "User", foreign_key: "parent_id" belongs_to :parent, class_name: "User" 它还与后模型关联: User has_many post def self.top_related_scored_by_user_id(user_id, max) where(:user_id => user_id
has_many :children, class_name: "User",
foreign_key: "parent_id"
belongs_to :parent, class_name: "User"
它还与后模型关联:
User has_many 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
每个Post对象都有一个score属性,我正在尝试查找给定用户及其子对象的Post,这些Post具有最高的分数,分数大于0,并且满足特定的属性。现在,我在我的Post模型中使用了这种方法:
User has_many 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的用户,还能够查找他们的孩子。我该怎么做
谢谢非常简单:
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
通过这种方式,您可以使用相同的函数轻松设置选项,并且它具有默认值,如果需要,可以覆盖这些值。Oh ok。因此,在使用该方法之前,我需要找出ID(父ID和子ID),对吗?是的,在使用该方法之前,您需要检索这些ID。如果ID数组可能很大,您可能需要使用子查询将工作卸载到数据库中。