Created
February 24, 2015 10:25
-
-
Save pixeltrix/df36f6e9105d9e6bc958 to your computer and use it in GitHub Desktop.
Comparison of has_many :through with writing a method
This file contains 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 Product < ActiveRecord::Base | |
has_many :category_products, dependent: :delete_all | |
has_many :categories, through: :category_products, ->{ order(:name) } | |
end | |
class CategoryProduct < ActiveRecord::Base | |
belongs_to :category | |
belongs_to :product | |
end | |
class Category < ActiveRecord::Base | |
has_many :category_products, dependent: :delete_all, ->{ order(:position) } | |
has_many :products, through: :category_products | |
end | |
# category.products generates 1 query: | |
# | |
# SELECT products.* FROM products | |
# INNER JOIN category_products | |
# ON products.id = category_products.product_id | |
# WHERE category_products.category_id = ? | |
# ORDER BY category_products.position | |
# vs. | |
class Product < ActiveRecord::Base | |
has_many :category_products, dependent: :delete_all | |
end | |
class CategoryProduct < ActiveRecord::Base | |
belongs_to :category | |
belongs_to :product | |
end | |
class Category < ActiveRecord::Base | |
has_many :category_products, dependent: :delete_all, ->{ order(:position) } | |
def products | |
category_products.preload(:product).map{ |c| c.product } | |
end | |
end | |
# category.products generates 2 queries: | |
# | |
# SELECT * FROM category_products | |
# WHERE category_products.category_id = ? | |
# ORDER BY category_products.position | |
# | |
# SELECT * FROM products WHERE id IN (?) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment