user1076802
user1076802

Reputation: 317

Correct method for custom Rails routing

In my routes I currently have resources :users and so I get the routes such as /users/id/ and /users/id/edit and so on...however, I am wanting to have the 'default' URLs for my pages begin with /name where name is the user's unique login name.

So, right now my routes file looks like this.

resources :users

match '/:name' => 'users#show_by_name'

Then in my users_controller.rb file, I have methods defined as such...

def show_by_name
  @user = User.find_by_name(params[:name])
  render 'show'
end

So, basically it is doing the same thing as def show but instead of an id being passed in the URL, it's a name.

In my views I am linking like this...

<li><%= link_to "My Profile", "/#{current_user.name}" %></li>

As opposed to using <li><%= link_to "My Profile", current_user %></li>

I am wondering if I am going about this the correct way. I feel like I am doing something unnecessary by using extra methods in my users_controller.

Would I be better off just removing the resources :users line and creating my own routes that are more suited towards the type of URLs I want on my application?

Thanks for your time.

Upvotes: 2

Views: 549

Answers (3)

Andrew Cetinic
Andrew Cetinic

Reputation: 2835

You might be better off overriding the to_param method in your User model. Rails has in built function for search friendly URL's

 class User < ActiveRecord::Base
     def to_param
        "#{user.name}"
     end
   end

Url's will generate as

user_url(@user)
#http://0.0.0.0:3000/users/andrew

# Controller
@user = User.find_by_name(params[:id])

Upvotes: 1

Jef
Jef

Reputation: 5474

Both Andrew and Martin are right (the FriendlyID gem actually uses the to_param override method), but you're asking two questions :

  • can I use another attribute instead of the default id as the id in the route ?
  • can I use a non-resourceful route ?

In both cases, the answer is yes. You may override the to_param method AND use a non-REST route such as :

match '/:id' => 'users#show'

Upvotes: 1

martinjlowm
martinjlowm

Reputation: 871

I would advice you to use FriendlyID, it's a neat gem that translates the :id to a value based on one of the table's columns. This could be a title for instance or name in your case.

I found it fairly easy to start using.

Ryan Bates talks about it in this screencast: http://railscasts.com/episodes/314-pretty-urls-with-friendlyid

For installation look here: https://github.com/norman/friendly_id

Upvotes: 1

Related Questions