在定义了tablename的已联接多态关联中进行搜索



我有两种型号的

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'

根据文档,多态关联依赖于模型上存在的两列。示例

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

然而,self-columns上的WHERE-子句有时会被神奇地修改:

User.where(thingable: 42)

中的结果

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

因此,如果我们想在这些多态性柱中的任何一个上进行筛选,我们会进行

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

最新更新