在我的 Rails 3.2.11 应用程序中,我有一个范围,我试图根据相关属性对其进行排序。在我的例子中,我有一个用户模型和一个配置文件模型。用户 has_one 配置文件,我的范围在配置文件表的属性上。范围如下:
在 User.rb
中:
def self.with_default_show
joins(:profile).where("profiles.show_all = true")
end
然而,我遇到的麻烦是试图声明订单。例如,运行:
joins(:profile).where("profiles.show_all = true").order("profiles.first_name DESC")
给我一个错误:
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
我知道我可以执行 .order("2")
但这会调用我的 Users 表中的第二列,而不是我的 Profiles 表中的第二列。如何正确地将此范围内的顺序设置为 profiles.first_name?
最佳答案
ORDER BY 子句只能在应用 DISTINCT 之后应用。
此外,您还必须明确选择您订购时所依据的条款。
User.select('profiles.*, profiles.first_name')
.joins(:profile)
.where("profiles.show_all = true")
.order("profiles.first_name DESC")
如上所示,为了让您的查询返回配置文件属性,您还必须明确选择它们。
关于sql - 在 has_one 关联的 Rails 3.2.11 中具有顺序的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441190/