module FormObject

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.

Public Instance Methods

save(*args) click to toggle source

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.

# File lib/form_object.rb, line 56
def save(*args)
  if valid?
    resource.save
  end
end
update(attrs) click to toggle source

implement update as per ActiveRecord::Persistence

# File lib/form_object.rb, line 82
def update(attrs)
  assign_attibutes(attrs)
  save
end
Also aliased as: update_attributes
update_attributes(attrs)
Alias for: update
valid?() click to toggle source

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)

Calls superclass method
# 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