我的新网址有这个结构:
module ApplicationHelper
def product_path(product)
unless product.category.nil?
cat = product.category
if cat.ancestry_depth.eql?(2)
product_long_path cat.root, cat.parent, cat, product
else
product_short_path cat.parent, cat, product
end
end
end
end
routes.rb文件
get "/(*root_id)_(*subcategory_id)_(*category_id)_(*id)" => "products#show", :as => :product_long
get "/(*root_id)_(*category_id)_(*id)" => "products#show", :as => :product_short
和我的节目动作
def show
@product = Product.find_by_slug params[:id]
cat = @product.category
raise NotFound unless cat.slug.eql?(params[:category_id]) and cat.root.slug.eql?(params[:root_id])
raise NotFound if cat.ancestry_depth.eql?(2) and !cat.parent.slug.eql?(params[:subcategory_id])
end
如何为"products/:id"
建立重定向,我有2类和3类深度的产品。
答案 0 :(得分:1)
我是以最明显的方式做到的:
ProductsController,显示动作
@product = Product.find_by_slug params[:id]
if @product.nil?
@product = Product.find params[:id]
redirect_to @product.redirect_string and return
end
产品型号中的
def redirect_string
if category.ancestry_depth.eql?(2)
"/#{category.root.slug}_#{category.parent.slug}_#{category.slug}_#{slug}"
else
"/#{category.parent.slug}_#{category.slug}_#{slug}"
end
end
但我不确定这是最优雅的解决方案,所以我可以开放另一种解决方案。