3.10.12

Route by name, Not by id.

Environment:

I'm using Ubuntu 12.04 64bit with RubyMine 4.5.4Ruby 1.9.3Rails 3.2.8.

Problem:

It's more a feature than a problem :P
I wanted to access my model by name and no by id for example:

By id:         |     By name:  
/friend/1     |   friend/john

 

Research:

By default controllers use the following code to get the required instance from the database:

@friend = Friend.find(params[:id])
respond_to do |format|
    format.html # show.html.erb
end

so first thing to try is:
@friend = Friend.find_by_name(params[:name])

ERROR!

So next i found map.connect...

map.connect 'friend/:name', :controller => 'friends', :action => 'show'
I found out that map.connect only available in rails 3.2 and was deprecated in rails 3.x 

 

Solution:

Have you ever heard of to_param ?
I just needed to add the following to my model (friend.rb):


def to_param
   name
end
And in the controller (friend_controller.rb):

@friend = Friend.find_by_name(params[:id]) 

No need to change anything in routes.rb!


ActiveAdmin fix:

For those of us who uses ActiveAdmin gem like me, there is another fix to be able to edit friends by name.
Add the following to your friends.rb: (ActiveAdmin.register Friend do)


before_filter :only => [:show, :edit, :update, :destroy] do
  @friend = Friend.find_by_name(params[:id])
end

No comments:

Post a Comment