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?
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])