0

I have two models: BigCategory and SmallCategory.

class BigCategory < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged

  has_many :small_categories, dependent: :destroy
end

class SmallCategory < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged

  belongs_to :big_category
end

I want to get all small_categories where big_category_id == params[:big_category_id].

SmallCategory.where(big_category_id: params[:big_category_id])

The usage of friendly_id is friendly.find:

SmallCategory.friendly.find(params[:id])

Here params[:id] is the record id. So the above case. Is there a way to get all small_categories with beautiful url?

s_zhang
  • 847
  • 2
  • 8
  • 16

1 Answers1

1

A better way to do it all together would be to use a single self-joining model to build a hierarchy:

class Category < ApplicationRecord
  belongs_to :parent, class_name: "Category"
  has_many :sub_categories, foreign_key: "parent_id", class_name: "Category"
end

If you then want to do a two level find you can do:

@parent = Category.includes(:sub_categories)
                  .find(params[:category_id])
@category = @parent.sub_categories
                   .friendly.find(params[:id])
max
  • 96,212
  • 14
  • 104
  • 165
  • Using a self join will let you build a hierarchy of any depth and also query for categories on the same table regardless of their "depth". – max Jan 30 '17 at 07:20