Active Recordを単独で使うときの備忘録です。データベースはPostgreSQLを使っています。
必要なものをインストール
Gemfile
ruby '4.0.5'
gem 'activerecord'
gem 'pg'
PostgreSQLの準備
--db_name table_nameはRailsの命名規則に則ります
createdb MyList
CREATE TABLE my_lists (
id int PRIMARY KEY,
item_name text not null,
price int not null
);
Modelの作成
test.rb
require 'active_record'
# pgはrequire不要
class MyList < ActiveRecord::Base
#WSL2環境の接続設定
establish_connection(
adapter: "postgresql",
host: "",
username: "[my name]", #OSのログインユーザー名
password: "[my password]", #OSのユーザーパスワード
database: "MyList"
)
#クラスメソッドの設定
def self.to_my_lists(id_no, item_name, price)
self.create(
id: id_no,
item_name: item_name,
price: price
)
end
end
items = [
[1, "apple", 100],
[2, "orange", 200]
]
items.each do |item|
MyList.to_my_lists(item[0], item[1], item[2])
end
p MyList.all
#=>
#<ActiveRecord::Relation [
# #<MyList id: 1, item_name: "apple", price: 100>,
# #<MyList id: 2, item_name: "orange", price: 200>
#]>
sqlで確認
psql MyList
MyList=> select * from my_lists;
id | item_name | price
----+-----------+-------
1 | apple | 100
2 | orange | 200
(2 rows)
備忘録
- establish_connectionメソッドのusernameは私の環境だとubuntuコンソールのプロンプト
AAAAA@BBBBB:~$のAAAAAの部分に表示されている名前 - establish_connectionメソッドのpasswordは私の環境だと
sudoコマンドを実行するときに入力するパスワード
Webスクレイピングとつなげて使うと便利です。