简体   繁体   中英

Rails route for current user's profile page

I'm looking for advice on the best way to create paths for a current user's profile page. Currently I only have users as a resource. You can visit any user's profile page by going to /users/:user_id. I also have member routes, for example, /users/:user_id/followers. I would like to be able to have the routes /profile and /profile/followers that will bring the current user to their profile page. So if my user id was 5 I could go to /profile and it would bring me to the same page as /users/5.

Note: I am also using devise

routes

  resources :users, only: [:show, :update] do
    member do
      get :following, :followers
    end
  end

users_controller

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

  def followers
    @user = User.find(params[:id])
    @title = "Followers"
    @users = @user.followers.active

    render 'show'
  end

  def following
    @user = User.find(params[:id])
    @title = "Following"
    @users = @user.followed_users.active

    render 'show'
  end

Is there a way I can use the users controller and the same actions

In the routes add

get 'profile', to: 'users#show'

In the action use current_user to find the user instead of User.find(params[:id] . Then you don't need to add the Id in the path.

In the show action you can add the following to be able to use both.

if params[:id]
  user = User.find(params[:id])
else
  user = current_user
end

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