简体   繁体   中英

rails extending devise registration form

I'm working on a system where it has 2 models, a user model, a school model.

I'm using devise registration for a regular user sign_up with 'role' as an additional field to indicate whether user is a regular user or a school_user.

For now there is a admin user who creates a new school record while user will register using devise/sign_up action. School doesn't have login information yet.

I can call schools/new action (as school signup link) to add a new school.

Instead I want to extend the devise registration for school which will sign up using 'new school signup link' as a new user (use email, password, role='school' for a user model) and other fields like name, address, etc. going into the regular schools table. This way school admin gets a login account as well.

How do I extend devise/registration form and create these 2 records?

I really appreciate few thoughts.

Override devise registrations route:

routes.rb :

devise_for :users, controllers: {registrations: 'registrations'}

Create controllers/registrations_controller.rb :

class RegistrationsController < Devise::RegistrationsController

    after_filter :add_school

    protected

    def add_school

        if resource.persisted? # user is created successfuly

          # resource holds all your form data. 
            resource.schools.build do |school|
                school.name = resource.school_name # form fields...
            end

            @school.save
        end
    end
end

To validate school fields add validations to your user.rb model

eg:

class User < ActiveRecord::Base
    # Include default devise modules. Others available are:
    # :confirmable, :lockable, :timeoutable and :omniauthable

    devise :database_authenticatable, :registerable,
           :recoverable, :rememberable, :trackable, :validatable

    validates :name,
              presence: true,
              length: {in: 1..50}

    validates :school_name,
              presence: true,
              length: {in: 1..50}
end

Just for reference:

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

    <div><%= f.label :school_name %>
        <br/>
        <%= f.text_field :name, autofocus: true %></div>

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

     # ...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM