Skip to content

Instantly share code, notes, and snippets.

@philk
Created October 30, 2009 17:34
Show Gist options
  • Save philk/222563 to your computer and use it in GitHub Desktop.
Save philk/222563 to your computer and use it in GitHub Desktop.
Sinatra file for wedding form
require "sinatra"
require "dm-core"
require "dm-validations"
require "json"
class RSVP
include DataMapper::Resource
property :id, Serial
property :first_name, String, :nullable => false, :message => "first_name"
property :last_name, String, :nullable => false, :message => "last_name"
property :email, String
property :attending, Boolean
property :created_at, DateTime
end
RSVP.auto_migrate! unless RSVP.storage_exists?
post '/rsvp' do
form = params["data"]
@res = []
@values = {}
form.each_pair do |i, person|
rsvp = RSVP.new
rsvp.attributes = {
:first_name => person["first_name"],
:last_name => person["last_name"],
:email => person["email"],
:attending => person["attending"],
:created_at => Time.now
}
@values.merge!({i => rsvp})
end
invalid = @values.select {|k, rsvp| !rsvp.valid?}
if invalid == []
@values.each_pair do |i, rsvp|
rsvp.save
@res.push({:index => i, :response => "success"})
end
else
@values.each_pair do |i, rsvp|
if rsvp.valid?
else
@res.push({
:index => i,
:fn => rsvp.errors[:first_name].to_s,
:ln => rsvp.errors[:last_name].to_s,
:email => rsvp.errors[:email].to_s
})
end
end
end
content_type :json
@res.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment