Monday, June 15, 2009

Use Permalink in Rails

It is easy to setup permalinks in Rails, so that your application url will show the meaningful path other than the default controller/action/id format.


To enable permalink in Rails, you need to add a column to store the permalink string (give it any name e.g. permalink). Then in your model, override the to_param metod to use the permalink as shown below:


 class Post < ActiveRecord::Base
has_many :comments, :dependent => :destroy

def to_param
"#{id}-#{permalink}"
end
end

You might encounter a strange error that says


modelname_url failed to generate......


I had this problem on my server and it turns out that I had a '.' in my permalink. '.' is used to set sub-domain in your url. Having '.' unintentionally will make url invalid.

No comments :

Post a Comment