Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebouchut/5a5e517512c2d7180052 to your computer and use it in GitHub Desktop.
Save ebouchut/5a5e517512c2d7180052 to your computer and use it in GitHub Desktop.
ActiveModel ActiveRecord generate error message
class User # class User < ActiveRecord::Base
include ActiveModel::Model #
attr_accessor :name, :age
validates :name, presence: true
validates :age, presence: true,
numericality: { only_integer: true, greater_than: 0 }
end
user = User.new(age: -99)
user.valid?
# Assuming the current locale is "en"
user.errors.full_messages # => [ "Name can't be blank", "Age must be greater than 0"]
user.errors.generate_message(:name, :blank) # => "can't be blank"
user.errors.generate_message(:age, :greater_than, {count: 0}) # => "must be greater than 0"
user.errors.full_message(:name, :blank) # => "Name can't be blank"
user.errors.full_message(:age, :greater_than, {count: 0}) # => "Age must be greater than 0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment