Last active
February 15, 2018 11:35
-
-
Save kleinjm/7b917c7b3fe4dae9ae05ebb212f58144 to your computer and use it in GitHub Desktop.
ActiveRecord locales (.yml) for Mongoid attribute validations
This file contains 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
# 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! |
This file contains 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
# config/application.rb | |
require_relative './mongoid_validations' | |
module ExampleApp | |
class Application < Rails::Application | |
config.after_initialize do | |
MongoidValidations.set_validation_file | |
end | |
end | |
end |
This file contains 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
# 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 |
This file contains 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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.