Home Active Record eagerly load polymorphic association
Reply: 0

Active Record eagerly load polymorphic association

user947
1#
user947 Published in April 26, 2018, 5:29 pm

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.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO