Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

Custom URL Routing in Ruby on Rails


I am currently learning ruby on rails with 3.0

I have created a post table with a column called friendly

Instead of using /post/:id I want to use /post/:friendly

meaning a URL will look like /post/post-title instead of /post/1

I have the controller framed properly with this code.

def show
  @post = Post.find(params[:friendly])

  respond_to do |format|
    format.html
    format.json { render :json => @post }
  end
end

But I am not sure how to change routes.rb to implement this change.

Right now it just says

resources :post

Thanks in advance for your help.


Solution

  • You can use to_param method on the model http://apidock.com/rails/ActiveRecord/Base/to_param

    If you keep object ID inside of the friendly, ex 1-some-name, 2-some-other-name you will not have to do anything else. Rails will strip id from the string and will use it to find your object. If you don't, you will have to change your controllers to use find_by_friendly(params[:id]) instead of find(params[:id])

    Another alternative is to use a gem like https://github.com/norman/friendly_id to accomplish this.