空的?使用default_scope(:order)

时间:2016-01-16 02:06:24

标签: ruby-on-rails postgresql activerecord default-scope

偶尔我想检查Person模型是否有任何组织。直截了当;使用@person.organizations.empty?。但是,加上我的default_scope(default_scope { order(:name) }),我收到了这个错误:

  

ActiveRecord :: StatementInvalid(PG :: InvalidColumnReference:错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中   第1行:......在哪里“关系”。“person_id”= $ 1 ORDER BY“organizat ...                                                                ^

     

:SELECT DISTINCT 1作为一个来自“组织”INNER JOIN“合同”ON“组织”。“id”=“合同”。“organization_id”INNER JOIN“关系”ON“合同”。“id”=“关系“。”contract_id“WHERE”relationship“。”person_id“= $ 1 ORDER BY”groups“。”name“ASC LIMIT 1):

我正在使用Postgres DB,我的(缩写)模型设置如下:

class Organization < ActiveRecord::Base
  has_many :contracts
  has_many :people, -> { uniq }, :through => :contracts

  default_scope { order(:name) }
end

class Person < ActiveRecord::Base
  has_many :relationships, :inverse_of => :person
  has_many :contracts, :through => :relationships
  has_many :organizations, -> { uniq }, :through => :contracts
end

class Contract < ActiveRecord::Base
  belongs_to :organization, touch: true

  has_many :relationships, :inverse_of => :contract
  has_many :people, :through => :relationships
end

到目前为止我尝试过的事情:

  has_many :organizations, -> { order(:name).uniq }, :through => :contracts

据说这会让主动记录看到事先发生的事情(事实并非如此)和

  has_many :organizations, -> { includes(:name).uniq }, :through => :contracts

修复了我在控制台中手动设置时的问题,但在应用程序本身没有帮助。如何强制ActiveRecord以不同方式格式化empty?查询或在我使用empty?时删除订单?

编辑:要清楚,我完全清楚使用@person.organizations.count == 0会起作用,并且可能还有其他一次性解决方案。但我正在寻找一般的,所以我不必一直重复自己。

1 个答案:

答案 0 :(得分:0)

@person.organizations.reorder('').empty? 

应该有效