Skip to content

Instantly share code, notes, and snippets.

@esparkman
Created May 4, 2018 15:22
Show Gist options
  • Select an option

  • Save esparkman/54cbf0985b5077fdd5f9fedd208e8098 to your computer and use it in GitHub Desktop.

Select an option

Save esparkman/54cbf0985b5077fdd5f9fedd208e8098 to your computer and use it in GitHub Desktop.
Form Object Example
# used to share results from one user to another
# ensures that valid data is supplied and errors out if the parameters are invalid
class BookingFormModel
include ActiveModel::Model
attribute :first_name, :string
attribute :last_name, :string
attribute :stay_duration_days, :integer
def persisted?
false
end
def save
@success = false
ActiveRecord::Base.transaction do
customer = Customer.new(customer_attributes)
booking = Booking.new(booking_attributes)
unless booking.save
flush_errors(booking)
raise ActiveRecord::RecordInvalid.new(booking)
end
unless customer.save
flush_errors(customer)
raise ActiveRecord::RecordInvalid.new(customer)
end
@success = true
end
@success
end
private
def flush_errors(model)
model.errors.each do |attribute, errors|
if respond_to?(attribute)
errors.each{ |error| errors.add(attribute, error) }
else
errors.each{ |error| errors.add(:base, error) }
end
end
end
def customer_attributes
attributes.slice(:first_name, :first_name)
end
def booking_attributes
attributes.slice(:stay_duration_days)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment