Method: Iry.handle_constraints

Defined in:
lib/iry.rb

.handle_constraints(model) { ... } ⇒ nil, Handlers::Model

Executes block and in case of constraints violations on model, block is halted and errors are appended to model

Examples:

Handle constraints for unique user

# The database schema has a unique constraint on email field
class User < ActiveRecord::Base
  include Iry

  unique_constraint :email
end

user = User.create!(email: "[email protected]")
fail_user = User.new(email: "[email protected]")
result = Iry.handle_constraints(fail_user) { fail_user.save }
result #=> nil
fail_user.errors.details.fetch(:email) #=> [{error: :taken}]

Parameters:

  • model (Handlers::Model)

    model object for which constraints should be monitored and for which errors should be added to

Yields:

  • block must perform the save operation, usually with save

Returns:

  • (nil, Handlers::Model)

    the model or nil if a a constraint is violated



110
111
112
# File 'lib/iry.rb', line 110

def self.handle_constraints(model, &block)
  TransformConstraints.handle_constraints(model, &block)
end