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

How can I change 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 route.rb file:

  resources :profiles 

I looked at similar answers regarding to_param , devise, or a nested loop or even an example in Rails 2.3 , but I could not find a way that works.

What changes should be made to profile / view / show.html.erb, routes.rb and model / profile.rb (if any) to change the routing from http: // localhost: 3000 / profiles / 1 to http: // localhost : 3000 / username ? I learn the basics, so I prefer not to use any gems or plugins.

+6
source share
2 answers

If you want to use usernames instead of identifiers, try friendly_id gem.

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

In the model:

 def to_param username end 

In the controller:

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

In the routes.rb file:

  match '/:id' => 'profiles#show' 
+5
source

Source: https://habr.com/ru/post/888514/


All Articles