Skip to content

Instantly share code, notes, and snippets.

@kleinjm
Last active February 15, 2018 11:35
Show Gist options
  • Save kleinjm/7b917c7b3fe4dae9ae05ebb212f58144 to your computer and use it in GitHub Desktop.
Save kleinjm/7b917c7b3fe4dae9ae05ebb212f58144 to your computer and use it in GitHub Desktop.
ActiveRecord locales (.yml) for Mongoid attribute validations
# config/locales/activerecord.yml
# Custom error messages for ActiveRecord and Mongoid Document validations.
#
# For a full list of validation options, see:
# http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models
en:
activerecord:
errors:
models:
order:
attributes:
size:
greater_than_or_equal_to: must be a positive number, dude.
name:
blank: cannot be let blank. Thanks!
# config/application.rb
require_relative './mongoid_validations'
module ExampleApp
class Application < Rails::Application
config.after_initialize do
MongoidValidations.set_validation_file
end
end
end
# config/mongoid_validations.rb
module MongoidValidations
# Point Mongoid Documents validations to use ActiveRecord validations
# that rails uses from the locales/en.yml or locales/activerecord.yml
def self.set_validation_file
Rails.application.eager_load!
Mongoid.models.each do |model|
class << model
def i18n_scope
:activerecord
end
end
end
end
end
# app/models/order.rb
# An example Mongoid Document
class Order
include Mongoid::Document
field :name, type: String
field :size, type: Float, default: -> { 0.0 }
validates :name, presence: true
validates :size, numericality: { greater_than_or_equal_to: 0.0 }
end
@coreycosman
Copy link

coreycosman commented Feb 15, 2018

Hey, I know this is a really old post, however, I found that just replacing active_record with mongoid on the config/locales/en.yml file works. Also, the quotes on the message seem to be necessary - I am using rails 5.1.4.

config_locales_with_mongoid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment