user4584963
user4584963

Reputation: 2523

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

Upvotes: 1

Views: 2587

Answers (1)

monty_lennie
monty_lennie

Reputation: 3341

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

Upvotes: 3

Related Questions