1

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

ActiveRecord::StatementInvalid (PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY 表达式必须出现在选择列表 LINE 1: ... WHERE "relationships"."person_id" = $1 ORDER BY "organizat... ^

: SELECT DISTINCT 1 AS one FROM "organizations" INNER JOIN "contracts" ON "organizations"."id" = "contracts"."organization_id" INNER JOIN "relationships" ON "contracts"."id" = "relationships"。 contract_id" WHERE "relationships"."person_id" = $1 ORDER BY "organizations"."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

据说这会让 activerecord 提前看到即将发生的事情(它没有)和

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

当我将它手动放入控制台时,它解决了这个问题,但对应用程序本身没有帮助。如何强制 ActiveRecord 以empty?不同的方式格式化查询或在我使用时删除订单empty?

编辑:需要明确的是,我完全知道使用@person.organizations.count == 0会起作用,并且可能还有其他一次性解决方案。但我正在寻找一个通用的,所以我不必不断重复自己。

4

1 回答 1

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

应该管用

于 2016-01-16T02:26:59.913 回答