[英]Rails 3 and clean URLs
將URL映射到數據庫ID的最有效方法是什么。
例:
/newspaper/article/how-interesting-is-internet
在路由中, newspaper_controller
獲取article
, how-interesting-is-internet
。
我應該在哪里以及如何存儲干凈的URL和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是一個很好的插件( https://github.com/norman/friendly_id )
它允許您指定將用於創建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方法創建自定義URL,例如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.