Skip to content

Instantly share code, notes, and snippets.

@frsyuki
Created July 24, 2012 03:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frsyuki/3167843 to your computer and use it in GitHub Desktop.
Save frsyuki/3167843 to your computer and use it in GitHub Desktop.
module UniqueConstraint
def self.included(model)
model.extend(ClassMethods)
end
module ClassMethods
def unique_constraint_violation_message
"#{name} must be unique"
end
def set_unique_constraint_violation_message(message)
define_attr_method :unique_constraint_violation_message, message
end
alias :unique_constraint_violation_message= :set_unique_constraint_violation_message
end
# override ActiveRecord::Base
def save!(*args, &block)
super(*args, &block)
rescue ActiveRecord::RecordNotUnique
raise $!.exception(self.class.unique_constraint_violation_message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment