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

感情迁移 提交于 2020-01-06 08:43:11

问题


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'

回答1:


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.



来源:https://stackoverflow.com/questions/55380556/how-to-create-an-account-when-and-assign-it-to-a-user-when-signing-up-via-cleara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!