如何在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
,但我收到了类似的错误。
答案 0 :(得分:1)
不幸的是,Rails并不聪明,无法通过where(accountant: { deactivated: true })
关联确定:accountant
与您的用户模型相关,因此您必须将其写为
TaxableEntity.joins(:accountant).where(users: { deactivated: true })
请注意它是users
,复数