Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 resource routing without an id

I am creating a blog application on Rails 3, and I want to override the default show route generated for a post by doing

resources :posts, :except => :show

Which generates, for the show route (had I not excluded it),

/post/:id

I want my route to look like this instead, where url_title is a string generated by my model on before_save, where it removes non alphanumeric characters and replaces spaces with hyphens.

/:year/:month/:day/:url_title

I'm trying to accomplish this with this bit of code:

match "/:year/:month/:day/:url_title", :to => "posts#show", :as => :post

In theory this should allow me to call post_path(@post) (where @post is an instance of my post class), and it should be able to sort this route out, and it almost works.

The only problem is that it tries to substitute the id of the post in for the year. The other fields fill in correctly. I think this is happening because rails has some default behavior that makes it really, really want to have the id in the url, and it doesn't trust me to use my own unique identifier (post.url_title, in this case).

I could be wrong about that though. Anyone have experience with this kind of routing, or know what's up?

like image 618
Zachary Wright Avatar asked Mar 16 '11 14:03

Zachary Wright


1 Answers

You can use to_param to craft the rails uses

class Post < ActiveRecord::Base
  ...
  def to_param
    "#{year}/#{month}/#{day}/#{title.parameterize}"
  end
end

More info: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param and http://www.seoonrails.com/to_param-for-better-looking-urls.html

If you go this route, you'll want to create a permalink attribute, and use Post.find_by_permalink(params[:id]) rather than Post.find(params[:id])

like image 123
Jesse Wolgamott Avatar answered Oct 12 '22 06:10

Jesse Wolgamott