Last active
May 14, 2017 22:16
-
-
Save ilake/1c344ba19aa642989e72 to your computer and use it in GitHub Desktop.
Mastering Rails Validations: Contexts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://blog.arkency.com/2014/04/mastering-rails-validations-contexts/ | |
# http://blog.arkency.com/2014/05/mastering-rails-validations-objectify/ | |
# The idea was, that it should not be possible to delete user who already took part of some important business activity. | |
class User < ActiveRecord::Base | |
has_many :invoices | |
validate :does_not_have_any_invoice, on: :destroy | |
def destroy | |
transaction do | |
valid?(:destroy) or raise RecordInvalid.new(self) | |
super() | |
end | |
end | |
private | |
def does_not_have_any_invoice | |
errors.add(:invoices, :present) if invoices.exists? | |
end | |
end | |
# allow us use two different kind context. | |
class Admin::UsersController | |
def edit | |
User.transaction do | |
@user = User.find(params[:id]) | |
if @user.valid?(:admin) && @user.valid?(:create) | |
@user.save!(validate: false) | |
redirect # ... | |
else | |
render # ... | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment