掲示板の作成です。DBにSQlite3、Deleteにjqueryを使っています。
C:/rails/sinatra/main.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | require 'sinatra' require 'sinatra/reloader' require 'active_record' ActiveRecord::Base.establish_connection( "adapter" => "sqlite3" , "database" => "./bbs.db" ) helpers do include Rack::Utils alias_method :h , :escape_html end class Comment < ActiveRecord::Base end get '/' do @comments = Comment.order( "id desc" ).all erb :index end post '/new' do Comment.create({ :body => params[ :body ]}) redirect '/' end post '/delete' do Comment.find(params[ :id ]).destroy end |
C:/rails/sinatra/views/index.erb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <! DOCTYPE > <html lang= "ja" > <head> <meta charset= "utf-8" > <title> BBS </title> </head> <body> <h1> BBS </h1> <ul> <% @comments . each do |comment| %> <li data-id= "<%= comment.id %>" > <%= h comment.body %> <span class = "deleteCmd" style= "cursor:pointer;color:blue" >[x]</span> </li> <% end %> </ul> <h2>Add New</h2> <form method= "post" action= "/new" > <input type= "text" name= "body" ><input type= "submit" value= "post!" > <script> $( '.deleteCmd' ).click(function(){ var el = $(this).parent(); if (confirm( 'are you sure to delete?' )){ $.post( '/delete' , { id: el.data( 'id' ) }, function(){ el.fadeOut( 800 ); }); } }) </script> </body> </html> |
C:/rails/sinatra/import.sql
1 2 3 4 | create table comments ( id integer primary key, body text ); |
ブラウザで確認してみてください。