Module: FormObject
- Extended by:
- ActiveSupport::Concern
- Includes:
- ActiveModel::Model
- Defined in:
- lib/form_object.rb
Overview
This module is to help with using Form Objects that are backed by ActiveRecord resources. The goal is to make a from object act like the underlying model class, but with its own set of validations.
Note that saving the form object requires validations in the form object to pass AND the validations in the underlying model object. Validation errors in the underlying model object will be included in the errors of the form object.
Defined Under Namespace
Modules: ClassMethods, DelegateEverything
Instance Method Summary collapse
-
#save(*args) ⇒ Object
Validate the form object and if it’s valid, call save on the underlying model object.
-
#update(attrs) ⇒ Object
(also: #update_attributes)
implement update as per ActiveRecord::Persistence.
-
#valid? ⇒ Boolean
The form object is valid when its validations pass AND the underlying model validations pass.
Instance Method Details
#save(*args) ⇒ Object
Validate the form object and if it’s valid, call save on the underlying model object. If there are multiple models that need to be saved you will need to reimplement this method.
56 57 58 59 60 |
# File 'lib/form_object.rb', line 56 def save(*args) if valid? resource.save end end |
#update(attrs) ⇒ Object Also known as: update_attributes
implement update as per ActiveRecord::Persistence
82 83 84 85 |
# File 'lib/form_object.rb', line 82 def update(attrs) assign_attibutes(attrs) save end |
#valid? ⇒ Boolean
The form object is valid when its validations pass AND the underlying model validations pass. If there are errors in the underlying resource, those errors are copied into the errors object for this form object so that they exist in a single place (easy for the form to work with)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/form_object.rb', line 65 def valid? result = [super, resource.valid?].all? # include any errors in the resource object in the +errors+ for this form object. This is useful # for uniqueness validation or existing validations in the model class so that they don't need # to be duplicated in the form object. (And especially uniqueness validators can only be run in # the ActiveRecord::Base model class. unless result resource.errors.each do |attr, error| errors[attr] << error unless errors[attr].include?(error) end end result end |