开发者

Rails 3 and clean URLs

开发者 https://www.devze.com 2023-02-19 03:05 出处:网络
What is the most efficient way to map URLs to database IDs. Example: /newspaper/article/how-interesting-is-internet

What is the most efficient way to map URLs to database IDs.

Example:

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

开发者_开发知识库In routing the newspaper_controller gets article and how-interesting-is-internet.

Where and how should I store the mapping for clean URLs and IDs?


FriendlyId is a good plugin for this (https://github.com/norman/friendly_id)

It allows you to specify a database column that will be used to create the id (name or description or whatever) and it takes care of making everything just work.


you should check out to_param method

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

So my suggestion is to store your clean_url right in your Article model with your ID and other stuff


I like the friendlyId approach too

The way I handle this sort of thing using the clasic blog example

Blog Controller {Fetches all posts by date}
Posts Controller {}

Routes

resource :blog do
  resources :posts      
end

App/Models/Post.rb

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

Then you end up with some nice paths

blog_path #Blog Index
blog_post(p) #Post Show


Use to_param method to create custom URLs such as 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
0

精彩评论

暂无评论...
验证码 换一张
取 消