Skip to content

Instantly share code, notes, and snippets.

@cooperq
Created May 3, 2011 19:28
Show Gist options
  • Save cooperq/954033 to your computer and use it in GitHub Desktop.
Save cooperq/954033 to your computer and use it in GitHub Desktop.
crud in sinatra
#here is app.rb:
get '/admin' do
protected!
@posters = Poster.all
@category_1_posters = @posters.all :category => 1
@category_2_posters = @posters.all :category => 2
@category_3_posters = @posters.all :category => 3
haml :'admin/index'
end
get '/admin/add' do
protected!
haml :'admin/add'
end
post '/admin/add' do
protected!
p = Poster.new params['poster']
tempfile = params['file'][:tempfile]
filename = params['file'][:filename]
directory = "public/posters"
path = File.join('public', 'posters', filename)
File.open(path, "wb") { |f| f.write(tempfile.read) }
p.image = filename
p.save
flash[:notice] = 'Poster was added successfully.'
redirect '/admin#top'
end
delete '/admin/delete/' do
protected!
poster = Poster.get(params[:poster])
poster.destroy
flash[:notice] = 'Poster was destroyed'
redirect '/admin#top'
end
end
# This is the model
class Poster
include DataMapper::Resource
property :id, Serial
property :image, String, :required => true
property :artist_name, String, :required => true
property :teacher, String, :required => true
property :school, String, :required => true
property :category, Integer, :required => true
property :votes_count, Integer
has n, :votes
def image_path
File.join File::SEPARATOR, "posters", self.image
end
end
-#admin/add.haml
%br
#vote-form
%form{ :action => '/admin/add', :method => 'post',:enctype => "multipart/form-data" }
%label{ :for => 'file' } Poster Image
%input{ :type => 'file', :name => "file", :id => 'file' }
%br
%label{ :for => 'artist_name' } Artist's Name
%input{ :type => 'text', :name => "[poster][artist_name]", id => 'artist_name' }
%br
%label{ :for => 'school' } School
%input{ :type => 'text', :name => "[poster][school]", id => 'school' }
%br
%label{ :for => 'teacher' } Teacher
%input{ :type => 'text', :name => "[poster][teacher]", id => 'teacher' }
%br
%label{ :for => 'category' } Category
%select{ :name => "[poster][category]", id => 'category' }
%option{ :value => 1 } k-2 grades
%option{ :value => 2 } 3-4 grades
%option{ :value => 3 } 5-6 grades
%br
%input{ :type => 'submit', :value => 'add new poster'}
-#admin/index.haml
%br
%h1 ADMIN SECTION
%a{ :href => '/admin/add' }
%h2 Add A New Poster
#vote-form
#error-container
%a{:name=>'top'}
= flash[:notice]
.poster-list#category_1
%h3 K-2 grades
= haml :'admin/poster', :locals => {:posters => @category_1_posters}
.clear
.poster-list#category_2
%h3 3-4 grades
= haml :'admin/poster', :locals => {:posters => @category_2_posters}
.clear
.poster-list#category_3
%h3 5-6 grades
= haml :'admin/poster', :locals => {:posters => @category_3_posters}
.clear
@jackaperkins
Copy link

thanks bro!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment