Created
May 4, 2018 15:22
-
-
Save esparkman/54cbf0985b5077fdd5f9fedd208e8098 to your computer and use it in GitHub Desktop.
Form Object Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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