Rails 3 - 如何设置 example.com/whatever-i-need 的路线

发布于 2025-01-01 08:08:32 字数 187 浏览 4 评论 0原文

我有一个小数据库,里面有我看过的电影。现在,当我想显示电影的详细信息时,所需电影的个人资料位于地址 example.com/movies/21 上。 但我希望在更好的 URL 地址上有每部电影的个人资料页面,例如 example.com/lords-of-the-rings

我该怎么做呢?

I have a little database with a movies that I saw. Now when I want to display a detail of a movie, so the profile of wanted movie is on the address example.com/movies/21.
But I would like to have a profile page of every movie on the nicer URL address, for example example.com/lords-of-the-rings.

How can I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

春夜浅 2025-01-08 08:08:32

在您的模型中,将 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

In your model, store the url name into a new field, like Movie.permalink

In config/routes.rb :

MyApp::Application.routes.draw do
  match "movies/:permalink" => "movies#show"
end

And in your controller :

class MoviesController < ApplicationController
  def show
    @movie = Movie.find_by_permalink( params[:permalink] )
  end
end

For more on routes in rails : http://guides.rubyonrails.org/routing.html

ㄟ。诗瑗 2025-01-08 08:08:32

考虑使用 slugged gem: https://github.com/Sutto/slugged

许多人喜欢这种方法。
这是轨道 3+

Consider using the slugged gem: https://github.com/Sutto/slugged

Many folks like this approach.
It's rails 3+

霞映澄塘 2025-01-08 08:08:32

只是为了帮助指导答案,您是否允许类似以下内容:

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])

Just to help guide the answers, would you allow something like:

http://example.com/movies/lord-of-the-rings

If so, grabbing the params[:id] from that URL is easy.

You can automate the generation of that last :id by changing to_param of the model:

class User < ActiveRecord::Base
  def to_param  # overridden
    name
  end
end

Then you could change the show method of the controller to reflect the new :id format.

user = User.find_by_name(params[:id])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文