简体   繁体   中英

I want to set authenticated users' root to a nested resource, their dashboard, instead of the home#index page non-authenticated users use as root

If I use the below code as is ( dashboards#show ), I get a record cannot be found error Couldn't find Dashboard without an ID because I don't have a user id in the path (I typically link to this dashboard using this: user_dashboard_path(current_user, current_user.dashboard) <-- cannot use that in routes.rb).

I think I need to pass the user into the code block that sets the root path, but I'm not sure how this would be accomplished.

Any tips?

Here is my entire routes.rb file:

MyApp::Application.routes.draw do
  resources :users do
    resources :dashboards, only: [:show, :edit, :update, :destroy]
  end

  authenticated :user do
    # Instead of the show action, I want to go to user_dashboard which is
    # GET    /users/:user_id/dashboards/:id(.:format)      dashboards#show
    root :to => "dashboards#show", as: :authenticated_root
  end

  root :to => "home#index"
  devise_for :users, :controllers => { :registrations => :registrations }

end

Option 1:
In your dashboards controller, change to:

@user = current_user
@dashboard = current_user.dashboard

This will also prevent users from seeing other user's dashboards.

Option 2:
Now, if users can see other user's dashboard fine, then change your route:

root :to => "dashboards#find", as: :authenticated_root

and in your dashboards controller:

def find
  redirect_to user_dashboard_path(current_user, current_user.dashboard)
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