Reputation: 145
I would like to get user profiles accessible from the URL: root/user/(username)
As of now I have it working with root/user/(id)
but i want it to be more user friendly and shareable with the username in the URL.
This is how I currently have it set up
#user_controller.rb
class UserController < ApplicationController
def profile
@user = User.find(params[:id])
end
end
#routes.rb
match 'user/:id' => 'user#profile'
#profile.html.erb
<h1><%= @user.firstname %>'s Profile</h1>
Basically what I'm trying to do is to change out :id
for :username
. I've created the usernames in the user models from devise so I know that is working. But right now when I try to get usernames in the URL I get Couldn't find User with id=username
.
Upvotes: 3
Views: 3144
Reputation: 950
Try friendly_id
. No need for any hacks in controller or model level.
Upvotes: 4
Reputation: 10198
Change your controller
class UserController < ApplicationController
def profile
@user = User.find_by_username(params[:username])
end
end
Then the route
match 'user/:username' => 'user#profile'
Upvotes: 6