0

I have the following models:

class User < ApplicationRecord
  has_one :card, as: :cardable
  scope :active, -> { where(active: true) }
end

class Organisation < ApplicationRecord
  has_one :card, as: :cardable
  scope :active, -> { where(active: true) }
end

class Card < ApplicationRecord
  belongs_to :cardable, polymorphic: true
end

I want to find all the cards whose associated User or Organisation is active.

I thought the following would work:

Card.includes(:cardable).where(cardable: {active: true})

But this throws an error:

ActiveRecord::EagerLoadPolymorphicError: Cannot eagerly load the polymorphic association :cardable

Is what I'm trying to do even possible with ActiveRecord? I've looked other questions with a similar title, but I am not sure the scenarios are similar enough to this one.

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189
  • From [the accepted answer](https://stackoverflow.com/a/16124295/6763239) for [the question](https://stackoverflow.com/questions/16123492/eager-load-polymorphic) you linked, did you try using a `belongs to` declaration like that under `# For Rails >= 4` in `Card` for both `:user` and `:organization`? Sorry, don't have time to set up and test a working example for myself. – Chapman Atwell Jan 12 '18 at 23:49

1 Answers1

0

I think this should work:

cardable_ids = User.active.pluck(:id) + Organisation.active.pluck(:id)
Card.where(cardable_id: cardable_ids)
fongfan999
  • 2,565
  • 1
  • 12
  • 21