0

メール ドメインに基づいて、会社のグループにユーザーを割り当てようとしています。私は考案+確認を使用しているので、正規表現の使用を避け(有効な電子メールであることを検証する必要はありません...)、これを簡単な方法で実行しようとしています。したがって、基本的には、サインアップ時にユーザーの company_id (そのテーブルと一致する) を強制的に割り当て、会社が存在しない場合はサインアップを許可しません。したがって、これは test@company.com と test@recruiting.company.com の両方で機能します。

ユーザーモデルで

before_create :company_placement

...

def company_placement
  user_domain = (: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
    (:company_id) = Company.find_by_domain(user_domain).id
  else
    #error out
  end
end

Railsコンソールでこれを段階的に行うと、うまくいくようです。しかし、実行するとコンソールで、

> user = User.create!(name: "test", email: "test@example.com", password: "foobar")

#<'User.... に対して未定義のローカル変数またはメソッド 'user' を取得します。

助けてくれてありがとう、まだレールを学んでいます...

4

1 に答える 1

1

だから私はこれでもう少し遊んで、私が好きな解決策を見つけたと思う

ユーザーモデルで

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

デバイス登録コントローラを作成 -- controllers/registrations _ controller.rb

新しい登録コントローラーで

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

ルート.rb

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

もっとエレガントな解決策があると確信していますが、これは私にとってはうまくいきます。コントローラーでエラー/フラッシュを処理し、会社が存在する場合、ユーザーはモデルを通じて会社に自動的に割り当てられます。

于 2012-11-06T07:04:35.313 に答える