Home Active Record eagerly load polymorphic association
Reply: 1

Active Record eagerly load polymorphic association

stephenmurdoch
1#
stephenmurdoch Published in 2018-01-12 14:05:30Z

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.

Phong Phan
2#
Phong Phan Reply to 2018-01-14 02:34:55Z

I think this should work:

cardable_ids = User.active.pluck(:id) + Organisation.active.pluck(:id)
Card.where(cardable_id: cardable_ids)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312929 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO