before_create in user model — set integer based on email (RAILS)

泪湿孤枕 提交于 2019-12-04 21:06:21

So I played with this some more and think i found a solution I like

in user model

before_validation :company_placement

...

def company_placement
  user_domain = self.email.split('@').last

  while user_domain.split('.').count > 2
    user_domain = user_domain.split('.', 2).last
  end

  if Company.find_by_domain(user_domain) != nil
    self.company_id = Company.find_by_domain(user_domain).id
  end
end

Created devise registration controller -- controllers/registrations _ controller.rb

in new registrations controller

class RegistrationsController < Devise::RegistrationsController
  before_filter :verify_company, only: :create

  private

    def verify_company
      build resource #necessary for devise

      user_domain = resource.email.split('@').last

      while user_domain.split('.').count > 2
        user_domain = user_domain.split('.', 2).last
      end

      unless Company.find_by_domain(user_domain) != nil
        flash[:error] = 'Sorry, your company does not exist yet'
        redirect_to root_path
      end
    end
end

routes.rb

devise_for :users, :controllers => { :registrations => "registrations" }

So im sure there is a more elegant solution, but this works for me. Handles the errors/flash in the controller, and then if the company exists, it the user gets auto assigned to the company through the model.

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