A
A
andreyjvasilev2017-01-27 16:37:02
Ruby on Rails
andreyjvasilev, 2017-01-27 16:37:02

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

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

Accordingly, @categories contains all root categories, and @categories[0].subcategories all child categories for the selected category. And you need to have no more than 5.
You need to achieve the result by modifying the query in the model connection:
has_many :subcategories, -> { order(:weight, :name).limit(5) }, foreign_key: :parent_id, class_name: 'Category'

But I need this connection without limit. Can I somehow set a limit for subcategories in the controller?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2017-01-27
@Dem1

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 question

Ask a Question

731 491 924 answers to any question