Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have example.com/username instead of example.com/user/1 in Rails 3?

How can I amend the routing from http://localhost:3000/profiles/1 to http://localhost:3000/myusername ?

I have a Profile model with the following table:

def self.up
    create_table :profiles do |t|
      t.string :username
      t.text :interest

      t.timestamps
    end
 end

And my routes.rb file:

  resources :profiles

I have looked at similar answers dealing with to_param, devise or nested loops or even an example in Rails 2.3, but i couldn't find a way that works.

What changes should I make to the profile/view/show.html.erb, routes.rb and model/profile.rb (if any) to amend the routing from http://localhost:3000/profiles/1 to http://localhost:3000/username? I'm learning from the basics, hence I rather not use any gems or plugins.

like image 394
Sayanee Avatar asked May 19 '11 09:05

Sayanee


2 Answers

If you want use usernames instead of IDs try friendly_id gem.

If you want to do it by yourself, the easiest way is to override method to_param in our model to return username, and then search in your controller by username.

In model:

def to_param
  username
end

In controller:

def show
  @user = User.find_by_username(params[:id])
end 

In routes.rb file:

  match '/:id' => 'profiles#show'
like image 104
Egor Avatar answered Nov 15 '22 10:11

Egor


This is what you need http://apidock.com/rails/ActiveRecord/Base/to_param

like image 34
Pravin Avatar answered Nov 15 '22 09:11

Pravin