Permalink
Browse files

Sinatra and ActiveRecord simple crud application

  • Loading branch information...
1 parent 1c51abb commit d312a0443622edcbf3d04c469473d5a2f744f61c @jcarlosgarcia committed Apr 9, 2012
View
7 sinatra_crud/config/database.yml
@@ -0,0 +1,7 @@
+development:
+ adapter: sqlite3
+ database: participant.db
+
+production:
+ adapter: postgresql
+ database: participant.db
View
55 sinatra_crud/crud.rb
@@ -0,0 +1,55 @@
+# crud.rb
+require 'sinatra'
+require 'active_record'
+
+configure do
+ # connect to the database
+ dbconfig = YAML.load(File.read('config/database.yml'))
+ ActiveRecord::Base.establish_connection dbconfig['development']
+
+ begin
+ ActiveRecord::Schema.define do
+ create_table :students do |t|
+ t.string :name, :null => false, :limit => 100
+ t.string :email, :null => false, :limit => 50
+ end
+ end
+ rescue ActiveRecord::StatementInvalid
+ # do nothing - gobble up the error
+ end
+end
+
+# define a simple model
+class Student < ActiveRecord::Base
+end
+
+# New participant
+get '/' do
+ begin
+ @list_students = Student.find(:all)
+ erb :new
+ rescue => ex
+ 'Cannot generate students list'
+ "#{ex.class}: #{ex.message}"
+ end
+end
+# Save the participant's info
+post '/' do
+ begin
+ @student = Student.new(:name => params[:name], :email => params[:email])
+ @student.save
+ redirect "/#{@student.id}"
+ rescue
+ redirect '/'
+ end
+end
+
+# Display participant's details
+get '/:id' do
+ begin
+ @student = Student.find(params[:id])
+ erb :show
+ rescue
+ redirect '/'
+ end
+end
View
BIN sinatra_crud/participant.db
Binary file not shown.
View
17 sinatra_crud/views/new.erb
@@ -0,0 +1,17 @@
+<h1>New Participant Form</h1>
+<p>Please enter the name and email id of the new participant. Have fun!</p>
+<form action="/" method="post" accept-charset="utf-8">
+ <input type="text" name="name" value="Name of participant..." id="name">
+ <input type="text" name="email" value="Email id..." id="email">
+ <input type="submit" value="... add the record!">
+</form>
+<table>
+ <tr><td>ID</td><td>NAME</td><td>EMAIL</td></tr>
+<%
+@list_students.each {|s| %>
+<tr><td><%= s.id.to_s %></td>
+ <td><%= s.name %></td>
+ <td><%= s.email %></td>
+</tr><% }
+%>
+</table>
View
2 sinatra_crud/views/show.erb
@@ -0,0 +1,2 @@
+<p><%= @student.name %> - <%= @student.email %></p>
+<p><a href="/">New Participant!</a></p>

0 comments on commit d312a04

Please sign in to comment.