2011-03-23 103 views
3

将URL映射到数据库ID的最有效方式是什么?Rails 3和干净的URL

实施例:

/newspaper/article/how-interesting-is-internet 

在路由newspaper_controller得到articlehow-interesting-is-internet

我应该在哪里以及如何存储干净的URL和ID的映射?

+0

为什么不使用例如文章标题为slu??像这样,只要标题/ slug在表中是唯一的,就不需要任何映射。 – polarblau 2011-03-23 22:04:21

回答

2

FriendlyId是一个很好的插件(https://github.com/norman/friendly_id

它允许您指定将用于创建id(名称或描述或任何)的数据库列,它负责使所有工作都正常工作。

2

你应该看看to_param方法

class Article < AR::Base 
    def to_param 
    self.cool_url # cool_url is column in your articles table with your clean url 
    end 
end 

所以我的建议是你的clean_url直接存储在您的ID和其他的东西,你的文章模型

1

我喜欢friendlyId做法太

我使用CLASIC博客例如

博客控制器处理这种事情的方法{获取日期的所有帖子}
帖子控制器{}

路线

resource :blog do 
    resources :posts  
end 

应用程序/模型/ Post.rb

class Post < ActiveRecord::Base 
    belongs_to :site 
    has_friendly_id :title, :use_slug => true 
end 

然后你结束了一些不错的路径

blog_path #Blog Index 
blog_post(p) #Post Show