在 Rails 的情况下如何使用 friendly_id?
How to use friendly_id in where case with Rails?
我有两个模型: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_categorieswhere 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都变得漂亮url?
一起完成这一切的更好方法是使用单个 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])
我有两个模型: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_categorieswhere 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都变得漂亮url?
一起完成这一切的更好方法是使用单个 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])