20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails Devise Ajax ログイン・登録

Last updated at Posted at 2015-06-20

DeviseをAjaxに対応する。API利用のトークン認証のやり方とかを参考に、まずはAjax対応のみ。

config/application.rb

    config.to_prepare do
      DeviseController.respond_to :html, :json, :js
    end

config/initializers/devise.rb

flashメッセージを取得するために以下のコメントアウトを外す
メッセージを直接セットするなら不要

config.navigational_formats = ['*/*', :html, :js]

sessions#createでwardenのrecallを実行するのに必要

config.http_authenticatable_on_xhr = false

flashを削除する

メッセージを直接セットするなら不要

    after_action :flash_clear
    def flash_clear
      if params[:format] == 'js'
        flash.clear
      end
    end

Devise以外のコントローラでformなどを使う(参考)

module ContentHelper
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end
end

confirmableを有効にする場合は事前にチェックする

class Users::SessionsController < Devise::SessionsController
  prepend_before_action :check_unconfirmed_user, if: -> { request.xhr? }
  skip_before_action :verify_authenticity_token, only: [:destroy, :create]

  def create
    if params[:format] == 'js'
      opts = auth_options
      opts[:recall] = "#{controller_path}#failure"
      self.resource = warden.authenticate!(opts)
      sign_in(resource_name, resource)
    else
      super
    end
  end

  def failure
    flash.now[:alert] = I18n.t('devise.failure.invalid')
    render partial: 'shared/js/notify'
  end

  private
    def check_unconfirmed_user
      puts params
      unless params[:user][:email].blank?
        user = User.find_by(email: params[:user][:email])
        if user && !user.confirmed?
          flash.now[:notice] = I18n.t('devise.failure.unconfirmed')
          render partial: 'shared/js/notify'
          return
        end
      end
    end

end

登録

class Users::RegistrationsController < Devise::RegistrationsController

  def create
    if params[:format] == 'js'
      flash.now[:notice] = I18n.t('devise.registrations.signed_up_but_unconfirmed')
    end
    super
  end

end

20
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?