DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on • Edited on

Devise Gem

Setting up Devise

rails generate devise:install

Set a root route

Devise wants us to define a root route with:

# config/routes.rb

root "boards#index"
Enter fullscreen mode Exit fullscreen mode

Generate user account

Use the generator to create the User model and routes.

rails generate devise user

rake db:migrate

Explore Devise-provided RCAVs

Restart the application server and find four new routes defined:

  • GET /users/sign_up
  • GET /users/sign_in
  • GET /users/sign_out
  • GET /users/edit

current_user

current_user is a helper method provided by the Devise gem used to access the logged-in user in controllers or views.

Add foreign key columns

Associate boards and posts with owners. Modify database tables to add a new foreign key column.

rails generate migration AddUserIdToBoards user_id:integer
Enter fullscreen mode Exit fullscreen mode
db:migrate
Enter fullscreen mode Exit fullscreen mode

and

rails generate migration AddUserIdToPosts user_id:integer
Enter fullscreen mode Exit fullscreen mode
db:migrate
Enter fullscreen mode Exit fullscreen mode

Add foreign keys in controller actions

Now that foreign key columns are in the database tables, visit any controller actions and make sure current_user.id is passed to any actions that need it (e.g. boards#create).

Update sample data task

user_id is not required in boards and posts. Open lib/tasks/dev.rake and update sample_data to include the foreign key when creating sample data.

Top comments (0)