Rails 4 - set a limit on the included model

I have Many-to-Many associations (this has been simplified for your convenience)

class Product
  has_many :categorizations
  has_many :categories, through: :categorization
end

class Category
  has_many :categorizations
  has_many :products, through: :categorization
end

I want to list the first 5 products of each category

But I can’t find a way to set the limit on enabled product. Below is my current request:

@categories = Category.includes(:products).all

The only solution I found is to add a condition to the model, for example:

# Solutions that I don't like
class Category
  ...
  has_many :products, include: product, limit: 5
end

Any suggestion? Thanks

+4
source share
2 answers

If you create a scope in a class Productto return the first five objects, you can call that scope in its relation. For example:

class Product
  has_many :categorizations
  has_many :categories, through: :categorization

  scope :first_five, -> { limit(5) }
end

Then you can do the following:

@categories = Category.includes(:products)
@categories.each do |category|
  puts category.products.first_five.inspect
end

And you should see no more than 5 products for each category.

+1

:

#app/models/product.rb
Class Product < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, -> { limit(5) }, through: :categorization
end

"Eager Loading Associations" ,


ActiveRecord

, , 5 . 5 , ActiveRecord Association Extenstions:

#app/models/product.rb
Class Product < ActiveRecord::Base
    has_many :categorizations
    has_many :categories, through: :categorization do
        def first_five
            limit(5)
        end
    end
end

@categories = Category.includes(:products).all
@categories.each do |category|
    puts category.first_five
end
+1

Source: https://habr.com/ru/post/1530556/


All Articles