LoginSignup
2
3

More than 5 years have passed since last update.

他DBを使っているRailsでPostgreSQLデータを扱う

Posted at

環境構築たまにしかやらないので、忘れる&
PostgreSQL 過去にチラッとしか触ったことないで
時間かかってしまったので、メモ

今回の前置き

環境
・プロジェクトで使っているのは、mysql、mongo
・Vagrant CentOS

やりたいこと
・PostgreSQLデータを一時的にいれて、Rails内で扱いたい
・今はとにかくローカルのみで扱う前提
・既にRailsが動く環境下で一時的なブランチで作業

※ 記憶を辿って書いたので、手順一部抜けてたらごめんなさい。

PostgreSQLデータを環境に用意

$ sudo yum install wget

$ wget http://yum.postgresql.org/9.3/redhat/rhel-6-x86_64/pgdg-centos93-9.3-1.noarch.rpm
$ sudo rpm -ivh pgdg-centos93-9.3-1.noarch.rpm

$ sudo yum install postgresql93
$ sudo yum install postgresql93-devel
$ sudo yum install postgresql93-server

$ sudo service postgresql-9.3 initdb
$ sudo /etc/rc.d/init.d/postgresql-9.3 start

$ su - postgres
$ passwd postgres

$ vi /var/lib/pgsql/9.3/data/postgresql.conf
  listen_addresses = '*'   # what IP address(es) to listen on;
$ vi /var/lib/pgsql/9.3/data/pg_hba.conf
local    all             all                   md5 # 追記

$ create database database_name;
$ psql database_name < dump.sql

$ sudo /etc/rc.d/init.d/postgresql-9.3 restart

※参考
VagrantのCentOSでPostgreSQLをRailsで使えるようにする - Qiita
http://qiita.com/ueki05/items/66597d40ee3914559655

PostgreSQL でパスワード認証を使う
http://net-newbie.com/postgres/password.html#h3_3

PostgreSQLの使い方
http://www.dbonline.jp/postgresql/

Rails側からアクセス

Gemfile

  gem 'pg'

$ bundle install

エラー

(省略)
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
--with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
(省略)

になるので

$ yum list available | grep postgres
$ sudo yum install postgresql-devel.x86_64
$ bundle install

※参考
[Rails] 開発環境用DBをSQLite3からPostgreSQLに変更する  - Qiita
http://qiita.com/cigalecigales/items/a12a780d300cca0844bd

database.yml

psql_development:
  adapter: "postgresql"
  encoding: "utf8"
  username: "postgres"
  password: "postgres"
  host: "127.0.0.1"
  database: "hoge_development"
  pool: 5

Model
複数のDBを使っているのでestablish_connectionで明示的に指定

class Client < ActiveRecord::Base
  establish_connection :psql_development
  self.table_name = "company"
end
$ bundle exec rails c
pry> Client.last

エラー

PG::ConnectionBad: FATAL:  password authentication failed for user "postgres"`

とかにぶつかるので

$ su postgres
$ vi /var/lib/pgsql/9.3/data/pg_hba.conf
 local    all             postgres                                ident 
$ psql
 ALTER USER postgres PASSWORD 'postgres';

参考
http://stackoverflow.com/questions/7695962/postgresql-password-authentication-failed-for-user-postgres

$ bundle exec rails c
pry> Client.last
=> #<Client … # ヽ(´∀`。)ノ゚.:。+゚とれた
2
3
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
2
3