我有一個存儲在City
表中的城市列表。假設我想在本例中通過resource.name
,city.name
生成動態路線。rail_resources使用資源名稱使用friendly_id gem
我希望能夠訪問/amsterdam
或/berlin
。怎麼樣?
對於我正在使用的信息friendly_id寶石已經有了slu column專欄,如果這樣做更有意義。
我有一個存儲在City
表中的城市列表。假設我想在本例中通過resource.name
,city.name
生成動態路線。rail_resources使用資源名稱使用friendly_id gem
我希望能夠訪問/amsterdam
或/berlin
。怎麼樣?
對於我正在使用的信息friendly_id寶石已經有了slu column專欄,如果這樣做更有意義。
假設你已經friendly_id設置正確:
match '/cities/:name' => 'cities#show'
或
resources :cities
從快速啓動爲friendly_id寶石:
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:在您的CitiesController
match '*id' => 'cities#show
然後:http://railscasts.com/episodes/314-pretty-urls-with-friendlyid?view=asciicast
在結束你的路由文件的,添加此
def show
@city = City.find(params[:id])
# ...
end
不知道這是否有幫助..但我已經把我在項目中使用的東西放在一起。
https://gist.github.com/1908782
它主要適用於我做什麼我的路線文件通常是相當簡潔。
它的美妙之處在於,如果您試圖訪問不存在的路徑,它將不會觸及任何路線!
只是一個側面說明,這是在4.0版本中打破。在撰寫本文時,您需要將以下內容放入您的gem文件中。
gem 'friendly_id', :git => 'git://github.com/norman/friendly_id.git'
或
gem 'friendly_id', :git => 'https://github.com/norman/friendly_id.git'
希望這有助於。