简体   繁体   中英

Rails - Devise - User Profile url with username on

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 .

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'

Try friendly_id . No need for any hacks in controller or model level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM