LoginSignup
19

More than 5 years have passed since last update.

SinatraでローカルはSQLite、heroku上はpostgreSQLを使用する方法(ローカル環境構築編)

Posted at

=======

・ディレクトリ構成は以下の通り

+ project_root/
  + vendor/             // gem管理用
    - bundle/
  + config/
    - database.yml      // DB情報管理
  + db/
    + migrate/
      -                     // マイグレーションファイル
    - development.db        // SQLite3テストDB
  + views/                  // ビューのテンプレート
    - index.erb
  - Gemfile
  - Procfile                // foreman設定用ファイル
  - Rakefile                //  rake設定用ファイル
  - config.ru               //  Rack設定用ファイル
  - main.rb             // コントローラ

Bundlerによるgem管理

Gemfileの設定は以下の通り

source "https://rubygems.org"
ruby "2.1.3"

gem "sinatra"
gem "activerecord"
gem "sinatra-activerecord", :require => "sinatra/activerecord"
gem "rake"

group :production do
  gem "pg"
end

group :development, :test do
  gem "sqlite3"
  gem "sinatra-reloader"
  gem "foreman"
end

各種gemをインストール *ローカルはpgは不要なので、withoutを指定する。

bundle install --path vendor/bundle --without production

Sinatraアプリケーションの設定

config.ru
require "rubygems"
require "bundler"
require File.dirname(__FILE__) + "/main"

use ActiveRecord::ConnectionAdapters::ConnectionManagement

run Sinatra::Application
web: bundle exec rackup config.ru -p $PORT
main.rb
# encodeing: utf-8
require "sinatra"
require "active_record"

require "sinatra/reloader" if development?

ActiveRecord::Base.establish_connection(ENV["DATABASE_URL"] || "sqlite3:db/development.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

DBを使用する為の設定

require "sinatra"
require "sinatra/activerecord"
require "sinatra/activerecord/rake"
config/database.yml
development:
  adapter: sqlite3
  database: db/development.db

rakeコマンドが使用可能なことを確認

bundle exec rake -T

#使用可能であれば以下のような項目が表示される。
rake db:create_migration
rake db:migrate

マイグレーションファイルの定義

bundle exec rake db:create_migration NAME=create_comments
#db/migrate/20141111121828_create_comments.rb
#上記のようなメッセージが表示される。
db/migrate/20141111121828_create_comments.rb
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :body

      t.timestamps
    end
  end
end

マイグレーション実行

bundle exec rake db:migrate
== 20141111121828 CreateComments: migrating ===================================
-- create_table(:comments)
   -> 0.0014s
== 20141111121828 CreateComments: migrated (0.0015s) ==========================

作成したアプリがローカルで動くことを確認する

foreman start

port=5000で起動するので適当に確認

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19