3

I'm trying to find all Foo's that don't have a Bar associated with them. I know this doesn't work but something along the lines of Foo.where(barable: nil).

Foo model

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

Bar model

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

Tables

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)
ferne97
  • 1,063
  • 1
  • 10
  • 20
  • Hi ferne97, check [this answer](https://stackoverflow.com/a/40511534/8759209), that should help – Artem Ignatiev May 21 '18 at 23:48
  • Your example doesn't reflect a true polymorphic use case, which hides the complexity here. You also need a `Baz` that is `barable`, which exposes the issue - you can't just query the join table id is null as you would for a normal has-many/belongs-to relationship because you don't know the join table name without asking the Rails class. – Woahdae Dec 12 '18 at 22:33

1 Answers1

0
Foo.joins('LEFT JOIN bars ON bars.foo_id = foos.id').where('bars.id is null') 
Pedro Fernandes
  • 366
  • 3
  • 11
  • `left_outer_joins` doesn't seem to work with polymorphic associations – ferne97 May 22 '18 at 01:14
  • True, I've changed to another way. This should work with polymorphic associations. @ferne97 – Pedro Fernandes May 22 '18 at 01:35
  • There is no `foo_id` on `bars` in his example. If there were, it'd be a has-many/belongs-to relationship, rather than a polymorphic one with `barable_id` and `barable_type` on `Bar` and nothing on any other model. – Woahdae Dec 12 '18 at 22:35