Rails 3 的动态路由 [英] Dynamic routes with Rails 3
问题描述
我的任务是按照路由模型开发 rails 应用程序.
I have a task to develop a rails application following the model for routing.
我需要有 PageController
和 Page
模型.页面网址必须类似于 /contacts、/shipping、/some_page
.
I need to have PageController
and Page
model. Page urls must be like /contacts, /shipping, /some_page
.
我还需要 CatalogController
和 Category
模型.类别网址必须类似于 /laptops,/smartphones/android
.
Also i need have CatalogController
and Category
model. Categories urls must be like /laptops, /smartphones/android
.
它将是 ProductsController
和 Product
模型,产品的 url 必须是 /laptops/toshiba_sattelite_l605
, /smartphones/android/htc_magic
And it will be ProductsController
and Product
model, urls of products must be line /laptops/toshiba_sattelite_l605
, /smartphones/android/htc_magic
我知道这个问题可以通过使用类似的 URL 来解决
I understand that this problem can be solved by using URLs like
/page/shipping
/catalog/smartphones/android
但客户不希望在 URL 中看到/page
"或/catalog
"的插入.
But the customer does not want to see the insertion of "/page
" or "/catalog
" in the URL.
请告诉我解决这个问题的方向.抱歉我的英语不好.
Please tell me the direction for solving this problem. Sorry for my bad English.
推荐答案
你必须写一个包罗万象"的规则:
You'll have to write a "catch-all" rule:
在 routes.rb 上:
On routes.rb:
get '*my_precioussss' => 'sauron#one_action_to_rule_them_all'
您宝贵的控制器:
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
然后你为每种种类"的元素编写一个视图:product.html.erb、category.html.erb 等
Then you write one view for each "kind" of element: product.html.erb, category.html.erb, etc.
确保您编写了find_by_slug
实现.
您可以将 one_action_to_rule_them_all
更改为 pikachu_i_choose_you
并将 SauronController
更改为 PokemonController
,也可以.
You can change one_action_to_rule_them_all
to pikachu_i_choose_you
and SauronController
to PokemonController
, will work too.
这篇关于Rails 3 的动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!