user7055375
user7055375

Reputation:

How do I create a dashboard link in my Rails user controller?

I’m using Rails 5. When my user is logged in, I want to replace the ‘/users/4’ action with a generic ‘/dashboard’ home link. I would also like the remove the user’s ability to typing in ‘/users/##’ into the browser, instead only allowing them to visit ‘/dashboard’. How do I do this? Currently, in my config/routes.rb I have

  get '/dashboard', to: 'users#show'
  resources :users

and in my users_controller.rb file I have

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

But currently when I visit “/dashboard” in my browser, I get the error

Couldn't find User with 'id'=

How can I set up my route to disable the show action but allow /dashboard to successfully navigate to the action above?

Upvotes: 1

Views: 917

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

What I like to do is something like this

  get '/dashboard' => 'users#show', as: :dashboard

now on your view you can do

link_to 'Dashboard', dashboard_path(current_user)

and in the controller you can do

  def show
    params[:id] == current_user.id unless params[:id]
    @user = User.find(params[:id])
    @user_subscriptions = UserSubscription.find_active_subscriptions_by_user(@user)
  end

Upvotes: 1

Related Questions