2015-05-11 65 views
0

如何在Rails中查詢別名關聯?查詢別名關聯

我有以下型號:

class TaxableEntity < ActiveRecord::Base 
    belongs_to :accountant, class_name: User, foreign_key: :accountant_id 
    has_many :invoices 
end 

class User < ActiveRecord::Base 
    has_many :taxable_entities, foreign_key: :accountant_id 
    enum role: [:account_holder, :accountant, :admin] 
end 

我試圖做到這一點查詢:

TaxableEntity.joins(:accountant).where(accountant: { deactivated: true }) 

而且我得到這個錯誤:

PG::UndefinedTable: ERROR: missing FROM-clause entry for table "accountant" 
     LINE 1: ..."."id" = "taxable_entities"."accountant_id" WHERE "accountan... 
                    ^
     : SELECT "taxable_entities".* FROM "taxable_entities" INNER JOIN "users" ON "users"."id" = "taxable_entities"."accountant_id" WHERE "accountant"."deactivated" = 't' 

我我也嘗試將accountant更改爲user,我也遇到了類似的錯誤。

回答

1

遺憾的是Rails是沒有足夠的智慧弄清楚,where(accountant: { deactivated: true })通過:accountant協會涉及到你的用戶模式,所以你必須把它寫成

TaxableEntity.joins(:accountant).where(users: { deactivated: true }) 

請注意,這是users,多

+0

非常感謝!這工作。 – 8vius