Created
January 20, 2023 11:45
-
-
Save iainbeeston/43cfa9b78848e7a00d8191d5d698ab6d to your computer and use it in GitHub Desktop.
Eager loading polymorphic associations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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