Monday, January 31, 2011

Restful routes for non ID( primary key ) rails 3

Lets suppose that you have a Profile model, and  you have a resources :profiles route.

Generally, profile_path will build a path with the profile object’s ‘id’ in it:
profile = profile.find_by_name('jaganreddy')
  profile_path(profile)  # => "/profiles/1"
You can override to_param in your model to make profile_path build a path using the profile’s name instead of the profile’s id:
class Profile < ActiveRecord::Base
    def to_param # overridding default behaviour
       name 
    end
 end
    
  

  profile = Profile.find_by_name('jaganreddy')
  profile_path(profile)  # => "/profiles/jaganreddy" 
 
Also take care for nested resources too
In your controller always looks for  
Profile.find_by_name(params[:id])