2016-01-16 26 views
1

偶爾我想檢查Person模型是否有任何組織。直截了當;使用@person.organizations.empty?。然而,再加上我default_scope(default_scope { order(:name) }),我得到這個錯誤:空?在ActiveRecord上使用default_scope失敗(:order)

ActiveRecord::StatementInvalid (PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list 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數據庫和我(略)模型設置如下所示:

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將工作,並且可能還有其他一次性解決方案。但我正在尋找一個一般的,所以我不必再重複自己。

回答

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

應該工作

+0

我正在尋找一個解決方案,這將使這可用一般;這個代碼庫已經足夠分割了,而不必把路標放在說'如果你想檢查這個空虛,使用計數== 0或重新排序' –

+0

你使用的是什麼版本的rails? –

+0

4.0.3,ruby 2.0.0 –

相關問題