oop-form-objects
Installation
SKILL.md
Form Objects
What it is
A Form Object is a plain Ruby class that includes ActiveModel::Model (and optionally ActiveModel::Attributes). It accepts form input, validates it, and on success dispatches to the appropriate models or services to persist. To Rails forms, views, and validations it looks and behaves like an ActiveRecord model.
Form objects are the right tool for:
- Forms that create/update multiple models atomically
- Virtual attributes (computed fields, confirmations, acceptance checkboxes) that have no DB column
- Wizard/multi-step forms where each step is validated independently
- Registration/signup flows where you don't want to add a callback or validation to
Userfor one context
Would a fat model do?
Add attributes and validations to the model directly if the form is simple and single-model. Extract a form object when:
- The form writes to 2+ models (e.g.
User+Profile+Organization) - There are virtual attributes (
password_confirmation,terms_accepted) that shouldn't exist on the model - The validation rules differ by context (sign-up has different rules than account settings)