使用Rails 3的动态路由

Bee*_*her 13 ruby ruby-on-rails url-routing ruby-on-rails-3

我有一项任务是根据路由模型开发rails应用程序.

我需要PageControllerPage模型.页面网址必须像/contacts, /shipping, /some_page.

我也需要CatalogControllerCategory模型.类别网址必须是这样的/laptops, /smartphones/android.

它将是ProductsControllerProduct模型,产品的网址必须是线/laptops/toshiba_sattelite_l605,/smartphones/android/htc_magic

我知道这个问题可以通过使用URL来解决

  • /page/shipping
  • /catalog/smartphones/android

但客户不希望在URL中看到" /page"或" /catalog" 的插入.

请告诉我解决这个问题的方向.对不起,我的英语不好.

Fáb*_*sta 49

你必须写一个"全能"规则:

在routes.rb上:

get '*my_precioussss' => 'sauron#one_action_to_rule_them_all'
Run Code Online (Sandbox Code Playgroud)

你珍贵的控制者:

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
Run Code Online (Sandbox Code Playgroud)

然后你为每个元素的"种类"写一个视图:product.html.erb,category.html.erb等.

确保编写find_by_slug实现.

您可以更改one_action_to_rule_them_allpikachu_i_choose_youSauronControllerPokemonController,也将工作.

  • 完全基于这个例子的upvoting;) (13认同)