LoginSignup
13
11

More than 5 years have passed since last update.

ActiveRecordを単体で使ってみる

Posted at

環境

  • ruby
    • 2.2.2p95
  • activerecord
    • 4.2.3

gemインストール

ActiveRecordをインストールする

$ gem install activerecord

MySQLに接続するためのgemをインストールする

$ gem install mysql2

早速使ってみる

database.ymlを準備する

DB接続設定の切り替えを簡単にできるように別ファイルに書き出す.

database.yml
db:
    production:
        adapter:    mysql2
        host:       localhost
        username:   <username>
        password:   <password>
        database:   <database>
    development:
        adapter:    mysql2
        host:       localhost
        username:   <username>
        password:   <password>
        database:   <database>

テーブルにアクセスするためのクラスを作る

self.table_nameに格納したテーブルにアクセスするためのクラス.
他のテーブルにもアクセスしたい場合は,それぞれに対応したクラスを作成する.

User.rb
require 'active_record'
require 'json'

# database.ymlを読み込んで,セットする.
conf = YAML.load_file('./database.yml')
ActiveRecord::Base.establish_connection(conf['db']['development'])


class User < ActiveRecord::Base
    self.table_name = <table name>
end

active_recordを使って,Userクラスに対応するテーブルにアクセスしてみる.

main.rb
require File.dirname(__FILE__) + '/User'

User.all
13
11
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
13
11