1

我有一个存储在City表中的城市列表。假设我想生成可通过 访问的动态路由resource.namecity.name在此示例中。

我希望能够访问/amsterdam/berlin。如何?

对于信息,我正在使用friendly_id gem,所以如果这更有意义的话,已经有了 slug 列。

4

3 回答 3

4

假设您正确设置了friendly_id:

match '/cities/:name' => 'cities#show'

或者

resources :cities

friendly_id gem的快速入门:

class City < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: :slugged
end

还:

# If you're adding FriendlyId to an existing app and need
# to generate slugs for an existing model, do this from the
# console, runner, or add a Rake task:

City.find_each(&:save)

这是一个 RailsCast:http ://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast

于 2012-01-17T05:38:51.523 回答
0

不知道这是否有帮助.. 但我已经汇总了我在项目中使用的要点。

https://gist.github.com/1908782

它主要适用于我所做的事情,因为我的路线文件通常非常简洁。

它的美妙之处在于,如果您尝试访问一条不存在的路径,它不会到达任何路线!

顺便说一句,这在 4.0 版本中被破坏了。在撰写本文时,您需要将以下内容放入您的 gemfile 中。

gem 'friendly_id', :git => 'git://github.com/norman/friendly_id.git'

或者

gem 'friendly_id', :git => 'https://github.com/norman/friendly_id.git'

希望这可以帮助。

于 2012-02-25T15:22:48.227 回答
0

在您的路线文件的末尾,添加以下内容:

match '*id' => 'cities#show

然后在您的 CitiesController 中:

def show
  @city = City.find(params[:id])
  # ...
end
于 2012-01-18T19:55:21.303 回答