The situation is such, there is a category model and two product and article models. The category model can have many products and many articles. How to combine them so that you can display all products and all articles on the categories / show page, as well as individually?

class Category < ApplicationRecord has_many :products has_many :articles has_ancestry :orphan_strategy => :rootify class Product < ApplicationRecord belongs_to :category class Article < ApplicationRecord belongs_to :category 

    1 answer 1

    You can try something like this:

     class CategoriesController < ApplicationController def show @category = Category.find(params[:id]) @products = Product.where(category_id: @category.id) @articles = Article.where(category_id: @category.id) end 

    And in the view, use variables with the desired objects, as needed.

    or (Rails Way) as advised D-side

     class CategoriesController < ApplicationController def show @category = Category.find(params[:id]) @products = @category.products @articles = @category.articles end 
    • What's wrong with @category.products and @category.articles ? The essence of associations is precisely to wrap the connection of the database level into something OOP-like. - D-side
    • And how on one page categories / show to display both products and articles that belong to the same category, so that they are sorted by name or date mixed, not first all products, and then all articles? - Petro Zendran