查询别名关联

时间:2015-05-11 16:31:55

标签: sql ruby-on-rails activerecord

如何在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 个答案:

答案 0 :(得分:1)

不幸的是,Rails并不聪明,无法通过where(accountant: { deactivated: true })关联确定:accountant与您的用户模型相关,因此您必须将其写为

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

请注意它是users,复数