Until now, I had implemented authentication functions such as login and logout by myself, but I would like to use devise when creating a portfolio this time, so I will leave this article as a memorandum of how to use it.
This article has been confirmed to work in the following environment. ruby 2.7.1 rails 6.0.3 devise 4.7.3
Added to Gemfile. I will translate it into Japanese in the second half, so I will include that gem as well.
Gemfile
gem 'devise'
gem 'devise-i18n'
gem 'devise-i18n-views'
Run bundle install
.
$ bundle install
Create related files.
$ rails g devise:install
Then the file will be created and the following English text will be displayed.
Running via Spring preloader in process 5911
create config/initializers/devise.rb
create config/locales/devise.en.yml
===============================================================================
Depending on your application's configuration some manual setup may be required:
1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
In production, :host should be set to the actual host of your application.
* Required for all applications. *
2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:
root to: "home#index"
* Not required for API-only Applications *
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
* Not required for API-only Applications *
4. You can copy Devise views (for customization) to your app by running:
rails g devise:views
* Not required *
===============================================================================
config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config/routes.rb
root to: 'homes#index'
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
$ rails g devise User
Looking at the created migration file, there are only email and password, so add any columns you want to add. Execute migration after adding.
$ rails db:migrate
At this point, open http: // localhost: 3000 / users / sign_up and a new registration page will be created. If you forget to add a column and want to add it later, execute the following. (This time, we will assume the addition of the username column)
$ rails g migration add_username_to_users username:string
Be sure to enter the username, so put a NOT NULL constraint.
db/migrate/XXXXXXXXXXXXXX_add_username_to_users.rb
class AddUsernameToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :username, :string, null: false
end
end
I want to customize the view, so execute the following.
$ rails g devise:views users
Reflects the edited contents of view.
config/initializers/devise.rb
#Config on line 247.scoped_views =Uncomment false and change to true
config.scoped_views = true
Allows usernames to be registered during sign_up.
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
end
end
$ rails g devise:controllers users
The controller file and English text are displayed.
Running via Spring preloader in process 9004
create app/controllers/users/confirmations_controller.rb
create app/controllers/users/passwords_controller.rb
create app/controllers/users/registrations_controller.rb
create app/controllers/users/sessions_controller.rb
create app/controllers/users/unlocks_controller.rb
create app/controllers/users/omniauth_callbacks_controller.rb
===============================================================================
Some setup you must do manually if you haven't yet:
Ensure you have overridden routes for generated controllers in your routes.rb.
For example:
Rails.application.routes.draw do
devise_for :users, controllers: {
sessions: 'users/sessions'
}
end
===============================================================================
Now let's check the current routing.
$ rails routes
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
...
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
If the Controller # Action part is devise / registrations, devise / sessions like this, the method to be defined from now on will not be reflected.
Override the route according to the English text that was displayed when you created the controller.
config/routes.rb
devise_for :users, controllers: {
registrations: 'users/registrations',
sessions: 'users/sessions'
}
Now that we have overridden it, check the current routing.
$ rails routes
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) users/sessions#new
user_session POST /users/sign_in(.:format) users/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) users/sessions#destroy
...
new_user_registration GET /users/sign_up(.:format) users/registrations#new
This will allow you to customize your controller. Define the method.
app/controllers/users/registrations_controller.rb
#Redirect destination after creating an account
def after_sign_up_path_for(resource)
root_path
end
#Redirect destination after editing the account
def after_update_path_for(resource)
root_path
end
app/controllers/users/sessions_controller.rb
#Redirect destination after logout
def after_sign_out_path_for(resource)
root_path
end
#Redirect destination after login
def after_sign_in_path_for(resource)
root_path
end
Now all redirect destinations are on the top page.
First, let's set the default language of this Rails application to Japanese.
config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module ConnectStudy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.i18n.default_locale = :ja #Add here
end
end
Generate a Japanese translation file for devise.
$ rails g devise:views:locale ja
This will be in Japanese. Don't forget to restart the server when you change the config.
devise also has a lot of useful helper methods, so I'd like to use them to develop apps efficiently.
Recommended Posts