Skip to content

Instantly share code, notes, and snippets.

@tbaba
Created March 4, 2014 02:17
Show Gist options
  • Save tbaba/9339047 to your computer and use it in GitHub Desktop.
Save tbaba/9339047 to your computer and use it in GitHub Desktop.
ActiveRecordのdestroyでバリデーションをやりたい ref: http://qiita.com/tbaba/items/9ea139dc77443e6d7be2
if @login_provider.destroy
redirect_to user_login_providers_path, notice: '削除しました'
else
redirect_to user_login_providers_path, notice: '削除できませんでした'
end
class LoginProvider < ActiveRecord::Base
belongs_to :user
before_destroy :user_should_have_at_least_one_login_provider
private
def user_should_have_at_least_one_login_provider
# もしユーザーのLoginProviderが1つしか無いのに、消そうとしていたら
if self.user.login_providers.length == 1
errors.add :base, '少なくとも1つ、ログイン用の認証が必要です'
return false
end
end
end
class User < ActiveRecord::Base
before_destroy :delete_all_his_posts
private
def destroy_all_his_posts
self.posts.delete_all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment