查询空的多态关联

时间:2018-05-21 21:48:24

标签: ruby-on-rails ruby ruby-on-rails-5

我试图查找没有与Foo相关联的所有Bar。我知道这不起作用,但有点像Foo.where(barable: nil)

Foo模型

class Foo < ApplicationRecord
    has_many :bars, as: :barable
end

酒吧模型

class Bar < ApplicationRecord
    belongs_to :barable, polymorphic: true
end

表格

Foo(id: integer, name: string, created_at: datetime, updated_at: datetime)

Bar(id: integer, barable_type: string, barable_id: string, created_at: datetime, updated_at: datetime)

1 个答案:

答案 0 :(得分:0)

Foo.joins('LEFT JOIN bars ON bars.foo_id = foos.id').where('bars.id is null')