21
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecordでSQLServerへ接続する

Posted at

前提

SQLServer2008のインストールされたWindowsマシン上での操作を想定しています。

gem を準備します。

source "https://rubygems.org"

gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter'
gem 'arel', '~> 3.0.2'
gem "tap"
gem "ruby-odbc"
gem "dbi"
gem "dbd-odbc"
gem "logger"

bundle installを実行

bundle install --path .bundle

SQLServerへの接続情報をYAMLに書きます。

development:
  adapter: "sqlserver"
  mode: "odbc"
  host: "localhost"
  username: "mssql_user"
  password: "mssql_password"
  database: "database name"
  dataserver: "Server name"
  dsn: "mssql dsn"  # 「コントロールパネル」 => 「ODBCデータソースアドミニストレータ」 で接続先のDBへのDSNを作成します。

ActiveRecordを使って接続します

# coding:utf-8
require "rubygems"
require "activerecord-sqlserver-adapter"
require "odbc"
require "yaml"
require "logger"
 
@setting = YAML::load(File.open("database.yml"))["development"]
ActiveRecord::Base.logger = Logger.new("debug.txt")
 
ActiveRecord::Base.establish_connection(
  adapter: @setting["adapter"],
  mode: @setting["mode"],
  host: @setting["host"],
  username: @setting["username"],
  password: @setting["password"],
  database: @setting["database"],
  dataserver: @setting["dataserver"],
  dsn: @setting["dsn"]
  )
 
class User < ActiveRecord::Base
  self.table_name = "user_table"  #接続したDBのテーブル名は「user_table」となっており、ActiveRecordの命名規則に反していたためtable_name にて設定
end
21
24
2

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
21
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?