LoginSignup
41
27

More than 5 years have passed since last update.

destroyのバリデーションするとき、return falseじゃなくてthrow :abortになったよ

Last updated at Posted at 2016-12-23

before_destroy

OmniAuthログインできるサービスをつくるとき、facebook,twitter,github,googleなど複数のプロバイダーとアカウントを連携させることがあります。
でも、すべてのアカウント連携を解除してしまうとセッションが切れた時にログインできなくなってしまうので少なくとも一つの認証用アカウントが必要です。

そんなときに、destroyメソッドにバリデーションをつけるために、Rails4まではbefore_destroyを使い、return falseを返すとコールバックがストップしてくれるのでそうしてました。

rails5からはthrow :abortになりました。

今まで通りerrors.full_messagesなどが使えます。

スクリーンショット 2016-12-24 0.22.29.png

social_profile.rb
class SocialProfile < ActiveRecord::Base
  belongs_to :user
  store :other
  validates :uid, uniqueness: { scope: :provider }, length: { in: 6..128 }
  validates :provider, inclusion: { in: Settings.auth_config.keys.map(&:to_s) }
  include Logic::SocialProfile
  include Logic::SocialProfile::InitializeWithCallbackInfo

  # before_destroyでdestroyメソッドを実行する前にバリデーションをかけます
  before_destroy :least_one

  private

  def least_one
    if self.user.social_profiles.count == 1
      errors.add :base, '少なくとも1つ、ログイン用の認証が必要です'
      # return false ではなく throw :abort
      throw :abort
    end
  end
end

railsは仕様変更も楽しいですね

41
27
1

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
41
27