Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

Sinatra+ActiveRecordでBBSを作ってみる

Sinatra 入門 - Qiita」は、Sinatra, ActiveRecordの初歩について学ぶのに非常に分かりやすくまとめられていると思います。概要を学ぶのに参考になったのですが、

以降、そのままだとコメントの削除機能など、動作しない部分があったので、自分の勉強を兼ねて作ってみました。

まず、ファイル構成は以下の通りです。

$ tree sinatra_lessons
sinatra_lessons
├── bbs.db
├── import.sql
├── main.rb
└── views
    └── index.erb

1 directory, 4 files

main.rb

# coding: utf-8
require "sinatra"
require "sinatra/reloader"
require "active_record"

ActiveRecord::Base.establish_connection(
  "adapter" => "sqlite3",
  "database" => "./bbs.db"
)

class Comment < ActiveRecord::Base
end

helpers do
  include Rack::Utils
  alias_method :h, :escape_html
end

get "/" do
  @title = "BBS(掲示板)"
  @comments = Comment.order("id desc").all
  erb :index
end

post "/new" do
  Comment.create({:body => params[:body]})
  redirect '/'
  erb :index
end

post "/delete" do
  Comment.find(params[:id]).destroy
end

import.sql

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

views/index.erb

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title><%= @title %></title>
</head>
<body>
  <h1><%= @title %></h1>
  <ul>
    <% @comments.each do |comment| %>
    <li data-id="<%= comment.id %>">
      <%= h comment.body %><button class="deleteCmd">Delete!</button>
    </li>
    <% end %>
  </ul>
  <h2>Add new</h2>
  <form method="post" action="/new">
    <input type="text" name="body">
    <input type="submit" value="post!">
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/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>

実行動画


Sinatraで掲示板を作ってみよう

参考