Rails中的漂亮路径 [英] Pretty Paths in Rails

查看:86
本文介绍了Rails中的漂亮路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别模型,我使用默认的脚手架 resources:categories 进行路由。我想知道是否可以将路径从 / category /:id 更改为 / category /:name 。我添加了:

I have a category model and I'm routing it using the default scaffolding of resources :categories. I'm wondering if there's a way to change the paths from /category/:id to /category/:name. I added:

match "/categories/:name" => "categories#show"

routes.rb中的资源行上方并更改了控制器中的 show 操作以执行以下操作:

above the resources line in routes.rb and changed the show action in the controller to do:

@category = Category.find_by_name(params[:name])

可以,但是像 link_to some_category 这样的魔术路径仍然使用:id 格式。

it works, but the 'magic paths' such as link_to some_category still use the :id format.

有没有办法做到这一点?如果这是一个坏主意(由于导轨在内部工作的某种可能方式),那么还有另一种方法可以做到这一点吗?这样,例如 / categories / music / categories / 3 都能起作用吗?

Is there a way to do this? If this is a bad idea (due to some possible way in which rails works internally), is there another way to accomplish this? So that /categories/music, for example, and /categories/3 both work?

推荐答案

Rails有一个漂亮的模型实例方法,称为 to_param ,它是路径使用的方法。它默认为 id ,但是您可以覆盖它并生成类似以下内容的文件:

Rails has a nifty model instance method called to_param, and it's what the paths use. It defaults to id, but you can override it and produce something like:

class Category < ActiveRecord::Base
  def to_param
    name
  end
end

cat = Category.find_by_name('music')
category_path(cat)  # => "/categories/music"

有关更多信息,请参见针对to_param的文档

For more info, check the Rails documentation for to_param.

编辑:

当涉及对URL不理想的类别名称时,您有多种选择。正如您所说,一种是在找到记录时使用连字符 gsub 空格,反之亦然。但是,更安全的选择是在类别表上创建另一列,称为 name_param (或类似名称)。然后,您可以使用它代替所有与路径和URL相关的业务的名称。使用 parameterize 变形器创建一个URL安全的字符串。我的操作方法如下:

When it comes to category names which aren't ideal for URLs, you have multiple options. One is, as you say, to gsub whitespaces with hyphens and vice versa when finding the record. However, a safer option would be to create another column on the categories table called name_param (or similar). Then, you can use it instead of the name for, well, all path and URL related business. Use the parameterize inflector to create a URL-safe string. Here's how I'd do it:

class Category < ActiveRecord::Base
  after_save :create_name_param

  def to_param
    name_param
  end

  private
    def create_name_param
      self.name_param = name.parameterize
    end
end

# Hypothetical
cat = Category.create(:name => 'My. Kewl. Category!!!')
category_path(cat)  # => "/categories/my-kewl-category"

# Controller
@category = Category.find_by_name_param(param[:id]) # <Category id: 123, name: 'My. Kewl. Category!!!'>

这篇关于Rails中的漂亮路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆