通过定义了table_name的联接多态关联进行搜索

问题描述

我有两个模型

class Profession < ApplicationRecord
    has_many :users
end

class User < ApplicationRecord

  self.table_name = 'accounts'

  belongs_to :scope,polymorphic: true

end 

查询

Profession.joins(:users).where(accounts: {scope: some_scope_variable })

我跑的时候得到

MysqL2::Error: UnkNown column 'accounts.scope' in 'where clause'

我也尝试过的是

Profession.joins(:users).where(users: {scope: some_scope_variable })

但它也不起作用,并给出类似的错误

MysqL2::Error: UnkNown column 'users.scope' in 'where clause'

解决方法


根据文档,polymorphic associations rely on two columns存在于模型中。例子

class User < ApplicationRecord
  belongs_to :thingable,polymorphic: true
end

这些列应位于users上:

  • thingable_id
  • thingable_type

如果要通过关联查询它们,则可以直接使用这些列,例如:

Profession.joins(:user).where(users: { thingable_id: 42,thingable_type: 'Foo' })

此外,我会重新考虑名称scope,因为Rails已经使用了它。


编辑:

提交以上答案后,我开始理解您的问题,对此表示抱歉。

我复制了它并使它像这样工作:

class Profession < ApplicationRecord
  has_many :users,as: :thingable # <-- this is missing in your case
end
class User < ApplicationRecord
  self.table_name = 'accounts'

  belongs_to :profession
  belongs_to :thingable,polymorphic: true
end

现在我们可以这样做:

Profession.joins(:users).where(accounts: { age: (20..30) })

联接表上的WHERE子句无需任何魔术和检查即可转换为SQL:

WHERE `accounts`.`age` BETWEEN 20 AND 30

而自列的WHERE子句有时会被神奇地修改:

User.where(thingable: 42)

产生

WHERE `accounts`.`thingable_id` = 42
--                         ^^^ added by Rails

因此,如果我们要对这些多态列中的任何一个进行过滤,则可以

Profession.joins(:users).where(accounts: { thingable_id: 111 })