How to Set up Nested Routes with Devise
I am using Devise for a small rails project and I want to create a new model, Setting. Setting belongs to the user and the user model has just one setting. Normally I would set up a simple nested route along the lines of:
resources :users do resource :setting end
The challenge is that devise uses a helper method to define the user routes. So instead of:
resources :users
Devise uses the following to create the user routes.
devise_for :users
The problem is that since devise_for is a helper method, the following is not a valid solution to adding the nested routes since it's not a resource route even though it looks very similar.
devise_for :users do resource :setting end
To create the nested routes, we need to go with:
devise_for :user, :path => "accounts"
resources :users do resource :setting end
Note that the devise_for was updated with the path "accounts". So now instead of routes for the authentication such as /users/sign_in, you have /accounts/sign_in. This is important in case that you ever need to add a UserController, it could create conflicts if you hadn't changed the path to accounts or some name other than users.
Since it is a one to one relationship between user and settings, on my nav bar I have a settings link that takes me right to the show page. With this type of relationship, there isn't a need for an index page. You don't need the id for the setting, just the user id for the user that owns the settings.
link_to "Settings", user_setting_path(current_user)
Now in the SettingsController, I add the following:
def show @setting = current_user.setting if !@setting redirect_to new_user_setting_path(current_user) end end
I check to see if a setting has been created, if not I redirect to the create action. The process is super simple but just a little out of the ordinary. Note to make sure that for the nested routes, use resource :setting if a one setting per user, and resources :settings if many settings per user.










