【Development environment】 macOS Catalina Version 10.15.3 ruby 2.5.1 Rails 5.2.4.2 visual studio code
If you create a login function with devise, it is originally only an email address and password, but it is a method to add columns for other items.
This time, add a column called company as an example.
$ rails g migration AddColumnToUsers company
Let's take a look at the created migration file. If you do not set the default value, an error will occur, so I will describe it.
Creation date and time_add_company_to_users.rb
class AddCompanyToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :company, :string, null: false, default: ''
end
end
When the description is finished, reflect it in the DB.
$ rails db:migrate
Add a form so that you can enter values in the columns you created. If you haven't created a devise view, create one.
$ rails g devise:views
registrations/new.html.erb
Add here---------------------------------
<div class="field">
<%= f.label :Please enter the hospital name and company name%><br />
<%= f.text_field :company, autofocus: true, class: "new_inform"%>
</div>
---------------------------------
<div class="field">
<%= f.label :Please enter your e-mail address%><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email", class: "new_inform" %>
</div>
<div class="field">
<%= f.label :Please enter your password%>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %>letter)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "new-password", class: "new_inform" %>
</div>
<div class="field">
<%= f.label :Please enter your password again%><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password", class: "new_inform" %>
</div>
<div class="actions">
<%= f.submit "sign up", class: "new_submit" %>
</div>
<% end %>
Use the configure_permitted_parameters method to set strong parameters.
devise\app\controllers\application_controller.rb
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:company])
end
Now it can be reflected in the DB.
I would appreciate it if you could point out any mistakes. Thank you for watching until the end.
Recommended Posts