How do you use Devise to register a user with additional attributes?

I am using Devise and I have a model User. By default, there is only a registration form with an email and a password. I want to add additional attributes. For example, an attribute college.

I followed this blog post to help. I have RegistrationsControllerone that overrides the default value RegistrationsController:

class MyDevise::RegistrationsController < Devise::RegistrationsController
  def create
    super
    resource.college = params[:resource][:college]
    resource.save
  end
end

However, I do not know how to update the user. I was looking through the Devise RegistrationController , but I can't figure it out. Does it have access to params[:resource]from the form?

This is the form in the view file:

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div><%= f.label :email %><br />
  <%= f.email_field :email, autofocus: true %></div>

  <div><%= f.label :password %><br />
    <%= f.password_field :password, autocomplete: "off" %></div>

  <div><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>

  <div><%= f.label :college %><br />
    <%= f.text_field :college %></div>
<% end %>

<%= render "devise/shared/links" %>
+4
source share
1

Rails and Devise RailsApps. , name :

.

:

# db/migrate/..._add_name_to_users.rb
class AddNameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :name, :string
  end
end

Devise, Rails 4.0 ( ).

:

# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  before_filter :update_sanitized_params, if: :devise_controller?

  def update_sanitized_params
    devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email, :password, :password_confirmation)}
    devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:name, :email, :password, :password_confirmation, :current_password)}
  end

end

:

# app/views/devise/registrations/new.html.erb
<h2>Sign up</h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
<p><%= f.label :name %><br />
<%= f.text_field :name %></p>

  <div><%= f.label :email %><br />
  <%= f.email_field :email %></div>

  <div><%= f.label :password %><br />
  <%= f.password_field :password %></div>

  <div><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></div>

  <div><%= f.submit "Sign up" %></div>
<% end %>

<%= render "devise/shared/links" %>

.

:

# config/routes.rb
RailsDevise::Application.routes.draw do
  root :to => "home#index"
  devise_for :users, :controllers => {:registrations => "registrations"}
  resources :users
end
+5

Source: https://habr.com/ru/post/1537048/


All Articles