2007年8月20日月曜日

RailsとPostgreSQLの接続を作る

RailsからPostgreSQLへ接続してみる

PostgreSQLのセットアップが完了したので、Ruby on Railsとの接続確立を確認します。

参考ページ
Postgresql on Rails and OSX (Potential Energy)

■RailsにPostgreSQL用のアダプタを与える

アダプタは2種類あるようです。どちらもgemコマンドでインストールできます。
違いは、わかりません。。1つ目の方法は、引数のパスを環境に合わせて変更する必要があります。
gem install postgres -- --with-pgsql-include-dir=/usr/local/pgsql/include --with-pgsql-lib-dir=/usr/local/pgsql/lib

gem install postgres-pr


結果ですが、1つ目の方法はパスをさらに設定してやらないとエラーになりました。
/etc/ld.so.confとやらに追記する方法もあるようですが、熟練者向けってどこかで書いてたのでやめました。

今回はサーバーを起動するユーザの(root).bash_profileファイルにLD_LIBRARY_PATHを設定しました。
以下を追加しました。
export POSTGRES_HOME=/usr/local/pgsql
export PGLIB=$POSTGRES_HOME/lib
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$PGLIB"
[root@mycentos ~]# cat .bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export POSTGRES_HOME=/usr/local/pgsql
export PGLIB=$POSTGRES_HOME/lib
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH":"$PGLIB"
unset USERNAME


.bash_profileを反映します。再読込み。
[root@mycentos ~]# source ~root/.bash_profile


2つ目の方法はインストールするだけで使えました。
うわさでは、1つ目のアダプタの方が処理が速いとか。。

■RailsのPostgreSQLへの設定をして接続を確認

続いて、RailsにDB接続確認用の画面を作ってみます。
任意の場所に任意のフォルダを作ります。
[root@mycentos var]# mkdir raily
[root@mycentos var]# cd raily
[root@mycentos raily]#


railsコマンドでDBテストプロジェクトを作成する
[root@mycentos raily]# rails dbtest
create
create app/controllers
create app/helpers
create app/models
     ・
     ・
     ・
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log
[root@mycentos raily]#


database.ymlを編集して、PostgreSQLのアダプタを使うようにします
viの使い方はviを使い倒そうで覚えました。
[root@mycentos raily]# cd dbtest/config
[root@mycentos config]# vi database.yml


とりあえず、development、test、productionの3箇所を以下のように変えました。
先に、pgAdminⅢを使ってスキーマを作成しました。pgAdminⅢはGUIなので方法は書きません。
(Railsのプロジェクトとスキーマは1対1でないと駄目だと思うよ)
adapterはそのままpostgresql、databaseは作成したDBの名前、usernameは作成したDBを編集できるロールの名前、passwordはそのロールのパスワード、encodingは作成したDBの文字コード(今回はUTF8で作成した)
adapter: postgresql
database: dbtest
username: ruby
password: rails
host: localhost
encoding: utf8
[root@mycentos config]# cat database.yml
# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql
# On MacOS X:
# gem install mysql -- --include=/usr/local/lib
# On Windows:
# gem install mysql
# Choose the win32 build.
# Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: postgresql
database: dbtest
username: ruby
password: rails
host: localhost
encoding: utf8

# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: postgresql
database: dbtest
username: ruby
password: rails
host: localhost
encoding: utf8

production:
adapter: postgresql
database: dbtest
username: ruby
password: rails
host: localhost
encoding: utf8


では、プログラムを作成します。コマンドで雛形を作成してくれます。助かります。
candyモデルを作成
[root@mycentos config]# cd ../
[root@mycentos dbtest]# ruby script/generate model candy
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/candy.rb
create test/unit/candy_test.rb
create test/fixtures/candies.yml
create db/migrate
create db/migrate/001_create_candies.rb
[root@mycentos dbtest]#


作成されたdb/migrate/001_create_candies.rbを編集して、テーブルを作成します。
以下のように編集
[root@mycentos dbtest]# vi db/migrate/001_create_candies.rb

class CreateCandies < ActiveRecord::Migration
def self.up
create_table :candies do |t|
t.column :name, :string, :limit => 30, :null => false
t.column :volume, :integer, :default => 0, :null => false
t.column :bb_date, :date
t.column :created_at, :timestamp
end
end

def self.down
drop_table :candies
end
end


rake db:migrateコマンドを実行する。
[root@mycentos dbtest]# rake db:migrate
(in /var/raily/dbtest)
== CreateCandies: migrating ===================================================
-- create_table(:candies)
NOTICE: CREATE TABLE will create implicit sequence "candies_id_seq" for serial column "candies.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "candies_pkey" for table "candies"
-> 0.0127s
== CreateCandies: migrated (0.0129s) ==========================================
[root@mycentos dbtest]#


んー出来たか不安だけど、次にcandyのscaffoldを作ります。
[root@mycentos dbtest]# ruby script/generate scaffold candy
exists app/controllers/
exists app/helpers/
exists app/views/candies
exists app/views/layouts/
exists test/functional/
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
identical app/models/candy.rb
identical test/unit/candy_test.rb
identical test/fixtures/candies.yml
create app/views/candies/_form.rhtml
create app/views/candies/list.rhtml
create app/views/candies/show.rhtml
create app/views/candies/new.rhtml
create app/views/candies/edit.rhtml
create app/controllers/candies_controller.rb
create test/functional/candies_controller_test.rb
create app/helpers/candies_helper.rb
create app/views/layouts/candies.rhtml
create public/stylesheets/scaffold.css
[root@mycentos dbtest]#


では、WEBrickを起動してみましょう。
[root@ndatacom dbtest]# ruby script/server
=> Booting WEBrick...
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2007-08-20 11:58:39] INFO WEBrick 1.3.1
[2007-08-20 11:58:39] INFO ruby 1.8.6 (2007-03-13) [x86_64-linux]
[2007-08-20 11:58:39] INFO WEBrick::HTTPServer#start: pid=23716 port=3000


画面でみれた。登録もできる。日本語もでた。

0 件のコメント: