我有两个模型:BigCategory和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
我想获取所有small_categories where big_category_id == params[:big_category_id]
。
SmallCategory.where(big_category_id: params[:big_category_id])
friendly_id的用法是friendly.find
:
SmallCategory.friendly.find(params[:id])
此处params[:id]
是记录ID。所以上面的情况。有没有办法让所有small_categories都有漂亮的网址?
答案 0 :(得分:1)
更好的方法是使用单个self-joining model来构建层次结构:
class Category < ApplicationRecord
belongs_to :parent, class_name: "Category"
has_many :sub_categories, foreign_key: "parent_id", class_name: "Category"
end
如果你想做两级别的发现,你可以这样做:
@parent = Category.includes(:sub_categories)
.find(params[:category_id])
@category = @parent.sub_categories
.friendly.find(params[:id])