ruby Sinatra 掲示板(bbs)

掲示板の作成です。DBにSQlite3、Deleteにjqueryを使っています。

C:/rails/sinatra/main.rb

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

<!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 src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
		<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

create table comments (
 id integer primary key,
 body text
);

ブラウザで確認してみてください。
bbs