【发布时间】:2012-02-24 03:15:55
【问题描述】:
我有一个小数据库,里面有我看过的电影。现在,当我想显示电影的详细信息时,想要的电影的个人资料在地址example.com/movies/21 上。
但我想在更好的 URL 地址上拥有每部电影的个人资料页面,例如example.com/lords-of-the-rings。
我该怎么做?
【问题讨论】:
标签: url ruby-on-rails-3.1 routes url-routing
我有一个小数据库,里面有我看过的电影。现在,当我想显示电影的详细信息时,想要的电影的个人资料在地址example.com/movies/21 上。
但我想在更好的 URL 地址上拥有每部电影的个人资料页面,例如example.com/lords-of-the-rings。
我该怎么做?
【问题讨论】:
标签: url ruby-on-rails-3.1 routes url-routing
在您的模型中,将 url 名称存储到一个新字段中,例如 Movie.permalink
在config/routes.rb:
MyApp::Application.routes.draw do
match "movies/:permalink" => "movies#show"
end
在你的控制器中:
class MoviesController < ApplicationController
def show
@movie = Movie.find_by_permalink( params[:permalink] )
end
end
有关 rails 路线的更多信息:http://guides.rubyonrails.org/routing.html
【讨论】:
考虑使用 slugged gem:https://github.com/Sutto/slugged
很多人喜欢这种方法。
这是rails 3+
【讨论】:
只是为了帮助指导答案,您是否允许以下内容:
http://example.com/movies/lord-of-the-rings
如果是这样,从该 URL 获取 params[:id] 很容易。
您可以通过更改模型的 to_param 来自动生成最后一个 :id:
class User < ActiveRecord::Base
def to_param # overridden
name
end
end
然后您可以更改控制器的 show 方法以反映新的 :id 格式。
user = User.find_by_name(params[:id])
【讨论】: