将URL映射到数据库ID的最有效方式是什么?Rails 3和干净的URL
实施例:
/newspaper/article/how-interesting-is-internet
在路由newspaper_controller
得到article
和how-interesting-is-internet
。
我应该在哪里以及如何存储干净的URL和ID的映射?
将URL映射到数据库ID的最有效方式是什么?Rails 3和干净的URL
实施例:
/newspaper/article/how-interesting-is-internet
在路由newspaper_controller
得到article
和how-interesting-is-internet
。
我应该在哪里以及如何存储干净的URL和ID的映射?
FriendlyId是一个很好的插件(https://github.com/norman/friendly_id)
它允许您指定将用于创建id(名称或描述或任何)的数据库列,它负责使所有工作都正常工作。
你应该看看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和其他的东西,你的文章模型
我喜欢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
使用to_param方法来创建自定义网址,如http://myblog.com/posts/2012-04-22/123-my-first-post.html
class Post < ActiveRecord::Base
def to_param
"/posts/#{published_at}/{id}-#{title.parameterize}.html"
end
end
为什么不使用例如文章标题为slu??像这样,只要标题/ slug在表中是唯一的,就不需要任何映射。 – polarblau 2011-03-23 22:04:21