LoginSignup
12
15

More than 5 years have passed since last update.

SinatraでSQLServerを参照する

Last updated at Posted at 2014-05-06

概要

Ruby、sinatra-activerecordからSQLServerの参照について簡単に纏める。

やりたいこと

Rubyを使用してSQLServerの既存テーブル(m_user)を参照する。

m_userのテーブル構造

UserID UserName
00000001 纏 流子
00000002 満艦飾 マコ

環境

  • Windows 8.1
  • Ruby 1.9.3p545
  • SQLServer 2008R2
  • sinatra (1.4.5)
  • activerecord-sqlserver-adapter (3.2.12)
  • tiny_tds (0.6.1 x86-mingw32)

1.GemFile

GemFile
source "https://rubygems.org"

gem 'activerecord-sqlserver-adapter', '3.2.12'
gem 'tiny_tds', '0.6.1'
gem 'sinatra', '1.4.5'

2.database.yml

database.yml
development:
  adapter:  "sqlserver"
  host:     "ホスト名(端末名,IPアドレス等)"
  username: "ユーザー名"
  password: "パスワード"
  database: "データベース名"

3.コントローラー

app.rb
# coding:utf-8
require 'activerecord-sqlserver-adapter'
require 'sinatra'
require 'tiny_tds'

ActiveRecord::Base.configurations = YAML.load_file('database.yml')
ActiveRecord::Base.establish_connection(:development)
use ActiveRecord::ConnectionAdapters::ConnectionManagement

class User < ActiveRecord::Base
#既存のテーブル名を使用(m_user)
    self.table_name = "m_user"
end

get '/' do
    @users = User.all(:order =>"userid")
    erb :index
end

4.ビュー

index.erb
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>ユーザ一覧</title>
</head>
<body>
    <table border ="1" CELLSPACING="0" CELLPADDING="0">
        <thead>
            <tr>
                <th>ユーザーID</th>
                <th>ユーザー名</th>
            </tr>
        </thead>
         <tbody>
            <% @users.each do |user| %>
        <tr>
            <td><%= user.UserID %></td>
            <td><%= user.UserName %></td>
        </tr>
        <% end %>
        </tbody>
    </table>
</body>
</html>

5.bundle install

bundle install --path vendor/bundle

6.実行

bundle exec ruby app.rb

7.ブラウザで確認

名称未設定-1.gif

12
15
0

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
12
15