Skip to content

Instantly share code, notes, and snippets.

@iainbeeston
Created January 20, 2023 11:45
Show Gist options
  • Save iainbeeston/43cfa9b78848e7a00d8191d5d698ab6d to your computer and use it in GitHub Desktop.
Save iainbeeston/43cfa9b78848e7a00d8191d5d698ab6d to your computer and use it in GitHub Desktop.
Eager loading polymorphic associations
class Picture < ApplicationRecord
belongs_to :employee , -> { left_joins(:picture).merge(Picture.of_employee) }, foreign_key: :imageable_id, inverse_of: :pictures
belongs_to :product , -> { left_joins(:product).merge(Picture.of_product) }, foreign_key: :imageable_id, inverse_of: :pictures
scope :of_employee, -> { where(imageable_type: "Employee") }
scope :of_product, -> { where(imegeable_type: "Product") }
end
class Employee < ApplicationRecord
has_many :pictures, -> { of_employee }, dependent: nil, foreign_key: :imageable_id, inverse_of: :employee
end
class Product < ApplicationRecord
has_many :pictures, -> { of_product }, dependent: nil, foreign_key: :imageable_id, inverse_of: :product
end
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment