views:

41

answers:

3

Hello I want to create seo optimize url in rails.Same like done in stackoverflow. Right now this is my url

http://localhost:3000/questions/56

I want to make it something like this:-

http://localhost:3000/questions/56/this-is-my-optimized-url

i am using restful approach. is there any plug-in available for this.

+1  A: 

Have a look here: http://ruby-toolbox.com/categories/rails_permalinks___slugs.html

auralbee
A: 

I know you asked for a plugin, but a dead simple approach is just to override the to_param method in your model. You can just append the seo name to the id.

For example:

class Question < ActiveRecord::Base
  #has attribute name.

  def to_param
    "#{id}-#{name.parameterize}"
  end
end

The path/url helpers will then generate a path like so:

show_question_path(@question)
>> /questions/12345-my-question-name

You do not need to do anything to your routes.

Your controller will remain Question.find(params[:id]) as the param will have to_i called on it, which will strip off the name and just return the id.

Alan Peabody
hey ur solution is quite good. can u explain it.its working.
piemesons
The _url and _path methods provided by the restful routes you define call to_param on the object passed in.So in this instance show_question_path(@question) is calling @question.to_param to get the id of the object and useing that to generate the route.The ActiveRecord::find will take the id at that point (12-example) and run to_i on it. the String::to_i function will convert any numeric characters in the beginning of a string to an integer, and ignore the rest.Thank explain things more fully?
Alan Peabody
A: 

I highly recommend looking into the friendly_id plugin. The FriendlyId Guide is a great place to start. I have been using this in production for a number of months and it works great.

Using the cached slugs feature makes this a very scalable solution. Additionally I'd recommend using it combination with stringex if you deal with non-ASCII characters.

Jason Weathered