0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

非Rails Active Recordの接続方法

0
Posted at

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スクレイピングとつなげて使うと便利です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?