ActiveModel: validations & naming
This course covers two parts of ActiveModel. The first is naming: model_name returns an ActiveModel::Name object with nine naming values plus human, used by partial lookup, form field names, route helpers and I18n. A namespace changes element, param_key, route_key and i18n_key in different ways. Overriding self.model_name lets a form object borrow another model's identity. The second part is validation: EachValidator classes for reusable per-attribute checks, and ActiveModel::Validator with validates_with for checks on the whole record.
What you'll learn
- ✓What each field of ActiveModel::Name holds and where Rails reads it
- ✓How a namespace changes element, param_key, route_key and i18n_key
- ✓Overriding self.model_name to borrow another model's naming, and the confusion it can cause
- ✓How human looks up a translation and falls back to a humanized name
- ✓Writing a reusable EachValidator class that respects allow_nil and allow_blank
- ✓Whole-record checks with ActiveModel::Validator and validates_with
ActiveModel::Naming: what model_name returns
"Form objects: complex logic" covered ActiveModel::Model, ActiveModel::Attributes, and how form_with calls model_name, persisted? and to_key on a plain Ruby object to build a working form. That course treated model_name as one method returning one thing Rails needs. This course picks up there.…
Read the full lesson free →Curriculum
7 lessonsActiveModel::Naming: what model_name returns
model_name returns a cached ActiveModel::Name object whose nine naming values plus human drive partials, form fields and routes.
route_key, param_key and i18n_key: namespacing changes each differently
On a namespaced class, element drops the module, param_key and route_key flatten it, and i18n_key uses a slash.
Overriding self.model_name: borrowing another model's identity
Passing a name to ActiveModel::Name.new in self.model_name makes a form object use another model's params, routes and I18n keys.
ActiveModel::Translation and .human: I18n lookup with a fallback
human runs an I18n lookup under the models scope and falls back to the humanized element when no translation exists.
ActiveModel::EachValidator: a reusable validator class
An EachValidator subclass defines validate_each once and is reused through validates with a key found by naming convention.
ActiveModel::Validator and validates_with: whole-record validators
ActiveModel::Validator receives the whole record, adds errors to :base, and is attached with validates_with instead of validates.
Putting it together: naming and validation, both reusable
One filter form combines an overridden model_name with the reusable EmailValidator, showing how both rely on shared Rails contracts.