Creating a Rails 7 application with Devise and roles
- Generate a new Rails application called “devise_roles”:
rails new devise_roles
2. Changes to the application directory:
cd devise_roles
3. Add the Devise gem to your Gemfile:
bundle add devise
4. Run the Devise installation generator:
rails g devise:install
5. Generate a User model with a role attribute:
rails g devise User role:integer
6. Open the generated migration file for the User model (`db/migrate/<timestamp>_devise_create_users.rb`) and set the default role to 0:
t.integer :role, default: 0
7. Run the database migration:
rails db:migrate
8. Generate a controller called “pages” with an action called “home”:
rails g controller pages home
9. Update the `config/routes.rb` file to set the root to the pages#index action:
root 'pages#index'
10. Create a view file for the home action (`app/views/pages/home.html.erb`) with the following content:
<% if current_user %>
<p>Hello <%= current_user&.email %></p><br>
<p>You are Role: <%= current_user&.role %></p><br>
<% if current_user.admin? %>
<p>User Total count <%= User.count %></p>
<% end %>
<%= link_to "Log Out", destroy_user_session_path, 'data-turbo-method': :delete %>
<% else %>
<p>You are not signed in</p>
<p>
<%= link_to "Sign up", new_user_registration_path %><br>
<%= link_to "Login", new_user_session_path %>
</p>
<% end %>11. Generate the Devise views for customization:
rails g devise:views
12. Update the sign-up form (`app/views/devise/registrations/new.html.erb`) to include `data-turbo: false` for the submit button:
<%= f.submit "Sign up", data: { turbo: false } %>
13. Update the session destroy link in the home view (`/app/views/devise/sessions/new.html.erb`) to include `’data-turbo-method’: :delete`:
<%= link_to "Log Out", destroy_user_session_path, 'data-turbo-method': :delete %>14. Add role enumeration to the User model (`app/models/user.rb`) using the `enum` macro and set a default role using the `after_initialize` callback:
enum role: [:user, :moderator, :admin]
after_initialize :set_default_role, if: :new_record?
def set_default_role
self.role ||= :user
end