我需要查询数据库并检索最近10个活动或拒绝的对象。我们使用以下代码:
User.where(status: [:active, :declined]).limit(10)现在我们需要获取每个状态的最后10个(总共20个用户)
我尝试过以下几种方法:
User.where(status: :active).limit(10).or(User.where(status: : declined).limit(10))
# SELECT "users".* FROM "users" WHERE ("users"."status" = $1 OR "users"."status" = $2) LIMIT $3这与前面的查询执行相同的操作,并且仅返回10个混合状态的用户。
如何通过一次查询获取最近10个活跃用户和最近10个拒绝用户?
发布于 2018-04-06 23:12:05
我不确定SQL是否允许做你想做的事情。我要尝试的第一件事是使用子查询,如下所示:
class User < ApplicationRecord
scope :active, -> { where status: :active }
scope :declined, -> { where status: :declined }
scope :last_active_or_declined, -> {
where(id: active.limit(10).pluck(:id))
.or(where(id: declined.limit(10).pluck(:id))
}
end然后你可以在别的地方做
User.last_active_or_declined()这样做的目的是执行两个不同的子查询,分别询问每个用户组,然后获取propper组ids中的用户。我会说您甚至可以忘记pluck(:id)部分,因为ActiveRecord足够聪明,可以将适当的select子句添加到您的SQL中,但我不能百分之百确定,而且我手头没有任何可以尝试这一点的Rails项目。
发布于 2018-04-06 23:09:01
limit不是#or关系的允许值。如果检查Rails代码,则引发的错误来自here
def or!(other) # :nodoc:
incompatible_values = structurally_incompatible_values_for_or(other)
unless incompatible_values.empty?
raise ArgumentError, "Relation passed to #or must be structurally compatible. Incompatible values: #{incompatible_values}"
end
# more code
end您可以在代码here中进一步检查哪些方法受到了限制
STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having, :unscope, :references]
def structurally_incompatible_values_for_or(other)
STRUCTURAL_OR_METHODS.reject do |method|
get_value(method) == other.get_value(method)
end
end您可以在Relation类here中看到限制是受限制的:
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering,
:reverse_order, :distinct, :create_with, :skip_query_cache,
:skip_preloading]因此,我担心您将不得不求助于原始SQL
发布于 2018-04-06 23:18:44
我不认为您可以使用单个查询来完成此操作,但您可以使用两个查询来完成此操作,获取记录it,然后使用这些记录it构建一个查询。
这并不理想,但由于您只是提取It,因此影响并不是很严重。
user_ids = User.where(status: :active).limit(10).pluck(:id) + User.where(status: :declined).limit(10).pluck(id)
users = User.where(id: user_ids)https://stackoverflow.com/questions/49695447
复制相似问题