How to set limit for query related models in Ruby on Rails controller?

The goal is to bring the root category and 5 child categories on the catalog page.

Communication in the model:

class Category < ApplicationRecord
 has_many :subcategories, -> { order(:weight, :name) }, foreign_key: :parent_id, class_name: 'Category'
end


Get the root category
@categories = Category.where(parent_id: nil).order(:weight, :name).all

Accordingly, @ "categories" contains all the root categories as @categories[0].all child subcategories for the selected category. And that would have to have no more than 5.

Need result was achieved by modifying the query in the context of the model:
has_many :subcategories, -> { order(:weight, :name).limit(5) }, foreign_key: :parent_id, class_name: 'Category'


But I need this relationship without limit. Can I somehow set a limit for subcategories in the controller?
August 19th 19 at 23:23
1 answer
August 19th 19 at 23:25
Doing so
# subcategory.rb
scope :recent, -> (count = 2) { limit(count) }

# category.rb

has_many :recent_subcategories, -> { recent }, class_name: Subcategory
# if you don't want to scope in subcategoty
has_many :recent_subcategories, -> { limit(2) }, class_name: Subcategory

# get
@categories[0].recent_subcategories

Find more questions by tags Active RecordRuby on Rails