我的任务是按照路由模型开发一个 Rails 应用程序。
我需要有 PageController
和 Page
模型。页面 url 必须类似于 /contacts、/shipping、/some_page
。
我还需要有 CatalogController
和 Category
模型。类别 url 必须类似于 /laptops、/smartphones/android
。
它将是 ProductsController
和 Product
模型,产品的 url 必须是行 /laptops/toshiba_sattelite_l605
, /smartphones/安卓/htc_magic
我知道这个问题可以通过使用像这样的 URL 来解决
/page/shipping
/catalog/smartphones/android
但是客户不希望在URL中看到“/page
”或“/catalog
”的插入。
请告诉我解决这个问题的方向。 抱歉我的英语不好。
最佳答案
你必须写一个“包罗万象”的规则:
在 routes.rb 上:
get '*my_precioussss' => 'sauron#one_action_to_rule_them_all'
您宝贵的 Controller :
class SauronController < ApplicationController
def one_action_to_rule_them_all
@element = find_by_slug(params[:my_precioussss])
render @element.kind # product, category, etc
end
end
然后为每种“种类”的元素编写一个 View :product.html.erb、category.html.erb 等。
确保编写您的 find_by_slug
实现。
您可以将 one_action_to_rule_them_all
更改为 pikachu_i_choose_you
并将 SauronController
更改为 PokemonController
,也可以。
关于ruby-on-rails - Rails 3 的动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4195880/