Answer the question
In order to leave comments, you need to log in
How to set a limit to query related models in Ruby on Rails in a controller?
The task is to display the root categories 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
@categories = Category.where(parent_id: nil).order(:weight, :name).all
has_many :subcategories, -> { order(:weight, :name).limit(5) }, foreign_key: :parent_id, class_name: 'Category'
Answer the question
In order to leave comments, you need to log in
Doing so
# subcategory.rb
scope :recent, -> (count = 2) { limit(count) }
# category.rb
has_many :recent_subcategories, -> { recent }, class_name: Subcategory
# если не хотите scope в subcategoty
has_many :recent_subcategories, -> { limit(2) }, class_name: Subcategory
# получите
@categories[0].recent_subcategories
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question