ruby-on-railsrubyuser-accountsclearance

How to create an account when and assign it to a User when signing up via Clearance in rails


What is the best way with Clearance to automatically create a an "Account" with a unique account_id (doesn't have to be UUID) and assign it to the new user on sign up?

I need to extend the clearance User sign up form and User controller to handle this but I'm having trouble getting this to work.

Should this be a before_filter on signup or part of the User create action?


Update: Adding some code for reference...

# app/controllers/users_controller.rb
class UsersController < Clearance::UsersController

  def create
    @user = user_from_params
    @account = account_from_params
    @user.account = @account

    if @user.save
      sign_in @user
      redirect_back_or url_after_create
    else
      render template: "users/new"
    end
  end

end

class AccountController < ApplicationController

  def create
    @account = Account.new(account_params)
  end

  private

  def account_params
    params[:account].permit(:id)
  end

end

<fieldset>
  <%= form.label :email %>
  <%= form.text_field :email, type: 'email' %>
</fieldset>

<fieldset>
  <%= form.label :password %>
  <%= form.password_field :password %>
</fieldset>


# Users & Clearance routes
  resources :passwords, controller: 'clearance/passwords', only: [:create, :new]
  resource :session, controller: 'clearance/sessions', only: [:create]

  resources :users, controller: 'clearance/users', only: [:create] do
    resource :password,
      controller: 'clearance/passwords',
      only: [:create, :edit, :update]
  end
  get '/login' => 'clearance/sessions#new', as: 'sign_in'
  delete '/logout' => 'clearance/sessions#destroy', as: 'sign_out'
  get '/signup' => 'clearance/users#new', as: 'sign_up'
  get '/users' => 'users#index'

Solution

  • I would hook into their controllers to keep things "in the gem" so to speak. This is how it works. Looks like you would hook into the controllers by overriding them like this:

    class UsersController < Clearance::UsersController
    
      def create
        @user = user_from_params
        @account = account_from_params
        @user.account = @account
    
        if @user.save
          sign_in @user
          redirect_back_or url_after_create
        else
          render template: "users/new"
        end
      end
    
    end
    

    Don't forget to update the routes and point them to this controller action. Now, you're sort of unhooking your controller create action from Clearance, but you're doing it in a "Clearance way" which seems most appropriate.