Ruby on rails 默认情况下,PostgreSQL按另一个属性排序,然后按我定义的任何属性排序?
我有一个IndexQuery,在这里我丰富了一组用户,然后对其应用了不同的过滤器Ruby on rails 默认情况下,PostgreSQL按另一个属性排序,然后按我定义的任何属性排序?,ruby-on-rails,database,postgresql,Ruby On Rails,Database,Postgresql,我有一个IndexQuery,在这里我丰富了一组用户,然后对其应用了不同的过滤器 class Users::IndexQuery def initialize(users) @users = users end def call @users.kept.created_desc .select( "users.*", "COALESCE(paid_invoices.paid_amount_ce
class Users::IndexQuery
def initialize(users)
@users = users
end
def call
@users.kept.created_desc
.select(
"users.*",
"COALESCE(paid_invoices.paid_amount_cents,0) AS paid_amount_cents",
"COALESCE(unpaid_invoices.unpaid_amount_cents,0) AS unpaid_amount_cents",
)
.joins(joins_paid_invoices, joins_unpaid_invoices, :subscription)
.includes(:subscription)
end
private
def joins_paid_invoices
@joins_paid_invoices ||= <<-SQL
LEFT OUTER JOIN (
SELECT invoices.user_id as user_id,
SUM(invoices.amount_cents) as paid_amount_cents
FROM invoices
WHERE invoices.status = 'paid'
GROUP BY user_id
)
AS paid_invoices
ON paid_invoices.user_id = users.id
SQL
end
def joins_unpaid_invoices
@joins_unpaid_invoices ||= <<-SQL
LEFT OUTER JOIN (
SELECT invoices.user_id AS user_id,
SUM(invoices.amount_cents) as unpaid_amount_cents
FROM invoices
WHERE invoices.status = 'unpaid'
GROUP BY user_id
)
AS unpaid_invoices
ON unpaid_invoices.user_id = users.id
SQL
end
end
但是,在控制台中使用.to_sql
在末尾运行查询会打印以下内容:
ORDER BY \"users\".\"id\" DESC, subscriptions.trial_end ASC"
无论是在控制器中还是在索引查询中,我都没有指定它应该按Users.id
排序。可能有什么问题?为什么默认情况下按该属性排序
编辑:我在IndexQuery中有一个用户分组.id
。这可能是问题所在吗?在Postgres 9.4+上,您可以大大简化这一点,从而为聚合函数的结果设置条件:
# see https://github.com/rubocop/ruby-style-guide#namespace-definition
module Users
class IndexQuery
def initialize(users)
@users = users
end
def call
@users.kept.created_desc
.joins(:invoices)
.group(:id)
.select(
User.arel_table[:*],
'SUM(invoices.amount_cents) FILTER (WHERE invoices.paid = true) AS paid_amount_cents',
'SUM(invoices.amount_cents) FILTER (WHERE invoices.paid = false) AS unpaid_amount_cents'
)
end
# conventiance method so that you don't need to call
# Users::IndexQuery.new(users).call
def self.call(users)
new(users).call
end
end
end
但是老实说,我不明白为什么你会将它提取到它自己的对象中,而不是仅仅在模型中创建一个作用域/类方法,因为这是一个非常复杂的解决方案。你能添加IndexQuery类吗?@SebastianPalma添加到OP中。User.default\u scopes
返回什么?@SebastianPalma它返回一个空数组[]@塞巴斯蒂安·帕尔玛,我想我找到了。它是IndexQuery开头的.created_desc作用域,按用户排序。id作用域:created_desc,->{order(id::desc)}。非常感谢。
# see https://github.com/rubocop/ruby-style-guide#namespace-definition
module Users
class IndexQuery
def initialize(users)
@users = users
end
def call
@users.kept.created_desc
.joins(:invoices)
.group(:id)
.select(
User.arel_table[:*],
'SUM(invoices.amount_cents) FILTER (WHERE invoices.paid = true) AS paid_amount_cents',
'SUM(invoices.amount_cents) FILTER (WHERE invoices.paid = false) AS unpaid_amount_cents'
)
end
# conventiance method so that you don't need to call
# Users::IndexQuery.new(users).call
def self.call(users)
new(users).call
end
end
end