开发者

url optimization in rails?

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/5开发者_Python百科6

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜