Skip to content

Instantly share code, notes, and snippets.

@brycesenz
Created January 16, 2014 04:34
Show Gist options
  • Save brycesenz/8449831 to your computer and use it in GitHub Desktop.
Save brycesenz/8449831 to your computer and use it in GitHub Desktop.
Example complex form saving for Daryl
#------------------------------------------------------------
# View
#------------------------------------------------------------
= form_for(claim...) do |f|
= text_field :user_lookup # An existing reference or data to create a new one
= text_field :provider_lookup # An existing reference or data to create a new one
= text_field :claim_name
= text_field :claim_amount
= text_area :claim_description
#------------------------------------------------------------
# Controller
#------------------------------------------------------------
class ClaimsController
...
def create
claim = ClaimCreator.new(params).process!
if claim.persisted?
redirect_to :show, :id => claim.id
else
render :new
end
end
end
#------------------------------------------------------------
# ClaimCreator Class
#------------------------------------------------------------
class ClaimCreator
def initialize(params)
@params = params
end
def process!
user = find_or_build_user(params.delete(:user_lookup))
provider = find_or_build_provider(params.delete(:provider_lookup))
claim = Claim.new(params.merge!(:user => user, :provider => provider))
ActiveRecord::Base.transaction do
user.save!
provider.save!
claim.save!
end
return claim
end
private
def find_or_build_user(lookup_id)
... # Your logic here
end
def find_or_build_provider(lookup_id)
... # Your logic here
end
end
#------------------------------------------------------------
# Models
#------------------------------------------------------------
# Don't change a thing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment