メイン

rails アーカイブ

2006年08月10日

InstantRails

本日は、次回の講義で利用する[ InstantRails ]をインストール。

Apacheも、MySQLもインストールしてあったので、
既存のApacheは起動しない。
既存のMySQLはアンインストール。(あんまり利用しないので)
これで、InstantRails付属のApacheとMySQLを利用する。

インストールは、すんなり。と言うか、ダウンロードして、InstantRails.exe をダブルクリックしただけ。
それで、http://localhost/ を見たら coming soon! と表示されました。

Apache の httpd.conf を見たら、いろいろと自動的に設定されていました。さすがインスタント!
PHPもMySQL、Rails もすぐ使える感じですね。

InstantRailsのスペック
Apache : Apache/1.3.33
PHP : 4.3.11RC1-dev
Ruby : 1.8.4
mysql : 3.23.49

rubyとmysqlにPathを通しました。
明日色々といじってみることとします。

2006年09月06日

Ruby on Rails

久々です。。
他の仕事に追われ記録を書けず、、だいぶ落ち着いたのでレッツカキカキ。


2006年9月4日(月)

InstantRails と radrails を利用した Ruby on Rails の実習です!
ついにここまで来た!

それにしても、吉田さんの講義をうけてから2ヶ月。
すごく成長した感があります。
技術面もそうですが、考え方や姿勢、歴史等をたくさん学んだ感じです。
揺らいでいた土台をがっちりと補強してくれたかんじでしょうか。
吉田さんに感謝!

まだまだ読んでない本がたくさんあるけど、コツコツ消化していこう。。

本で言うと6章くらいまで進みました。


来週からH氏とペアプロで開発を行うのですが、
オブジェクト指向で、しかもペアプロで開発するのは初めてなので、
不慣れな部分が多く、戸惑いながら行うと思いますが、
どんどん経験を積まないと解決されない問題だと思いますので、
とにかく経験を積んでゆこうと思います。


最近、少しRubyから離れてしまい、、基本的なことも少し忘れかけている。。。
一日少しで触ることが大切なんだなと思った。。
継続は力なり!

2006年09月12日

とにかく実践あるのみ!

最近Railsの学習に遅れをとっている・・・。巻き返さないと!
ということで、本日の学習の記録。

上記の本の第Ⅱ部「アプリケーションを構築する」第5章~第11章までを、
Tさんと一緒に先生から解説を受ける。

第5章~第11章はRailsを使った、アプリケーションの実践だ。
100ページくらいあって、とにかくババーっと4時間説明をうけた。
付きっ切りだったので、他の受講者の方々には少し申し訳なかったかな。。。

本の上では、「ふむふむ、おー」と分かるのだが、
やはり、実際にコードを書かないと実感がわかない。
本日これから、ババっと書いてみようと思う。

Rubyの基礎知識はだいぶ慣れてきたと思うので、
オブジェクト指向を体に染み込ませることが重要かなと思う。

とにかく実践あるのみ!あせらずゆっくり、でも早く。
日々コツコツ積み上げることが重要だな。
無理やりにでも時間とらないと。。

2006年10月05日

学習少しずつ復活

通常は朝10時出社だが、
本日は、朝9時に出社。

そもそも、僕自身朝方であると思われるので、この方が体に良い。
朝遅く起きて、夜遅くまで作業していると言うのは、どうも体に合わないようだ。。。
ということで、朝早く起きて、夜早く寝るという生活リズムを作ろうと実践中。
なので、朝早く来たら、24時まで仕事していると言うのはNG!!
20時くらいには退社しますゆえ。。その分、早く来ます。

この方が、すべてにおいて都合が良いのだ。うんうん。

と言うことで、本日から開始の「早寝早起きプロジェクト」。

本日は、すっかり遠退いていたRuby on Rails を復習。

学習時間は朝9時~朝10時。
「RailsによるアジャイルWebアプリケーション開発」の4章から6章を復習。
さすがに、2度くらいやっているので、サラサラ進みました。

コントローラーとビューの関係。モデル、スカフォルド・・・etc
みたいなRailsの基本とをやりました。

基本は大切。

明日は7章からやろう!
とりあえず、Depot storeを完成だ!

2006年10月06日

http://api.rubyonrails.org/

railsの学習でこのページはかかせません。

http://api.rubyonrails.org/

@content_for_layout

今日は、あまり進みませんでした。。

「RailsによるアジャイルWebアプリケーション開発」の7章をやりました。

@content_for_layout

/app/views/layouts ディレクトリは便利です。

index.rhtmlの使い方も分かりました。

来週からずっと朝早く来てやるぞ!

2006年10月10日

belongs_to :[table name]

本日も少し進展、夜にもう少しやりたい。とりあえず朝の部分をカキカキ。

「RailsによるアジャイルWebアプリケーション開発」の8章の8.1, 8.2をやりました。

たとえば、
データベースが、

create table(
id int primary key,
・・・
);

create table chidren(
id int primary key,
parent_id int references parents(id),
・・・
);

があったとします。
それで、Railsクラスに以下のように記述されていると、

class Parent < ・・・
・・・
end

class Child < ・・・
belongs_to :parent
end

belongs_to の関係により、parentテーブルのid列を参照する parent_id が Children テーブル内に存在すると想定されることになります。

ActiveRecord::Base は便利です。

2006年10月17日

環境設定に苦しむ・・・

hさんのruby on rails で開発中のアプリを僕のローカルでも動かそうと環境設定。

が・・・かなり苦しむ。。。
日本語(utf-8)が化けてしまって、構文エラーが起こる。。。
とりあえず、見れるようになったので、そのときの作業を記録。

○インストールの順番

1.InstantRails のダウンロード
  こちらから InstantRails-1.3a-win.zip をダウンロード。
  ※hさんの環境と同じにするため。最新はダウンロードしなかった。

2.InstantRails のインストール
  インストールと言っても、難しいことはない。
  どこかに(ちなみに、僕は C:\instantrails\ )フォルダをつくり、そこにコピー。

3.path の設定。
  ***********
  C:\instantrails\ruby\bin;
  C:\instantrails\mysql\bin;
  ***********

4.RadRails インストール
  ※これは、以前やっていたので、インストール内容は省く。
  あ、文字コードの設定だけ記録。
  ***********
  Window => Perferences => General => Workspace を開く。
  Text file encoding の Other をセレクトして、UTF-8 を選択する。
  **********
  そうすると、RadRails はファイルをUTF-8の文字コードで表示してくれる。

5.Railsバージョンアップ
  gem install rails

6.InstantRails の mysql の文字コードを utf-8 に設定
  ・my.ini に以下の行を追加。
   *****************
   default-character-set = utf8
   *****************

7.InstantRails 起動
  InstantRails.exe を起動。
  ファイルの場所は、 C:\instantrails\www\

8.http://localhost/ をブラウザで見る。
  ***********
  coming soon!
  ***********
  とりあえず、InstantRails はOK。

9.RadRails で 新しい Rails Project を作成する。
  Project 名は internal_management とする。

10.Rails Project でできたファイルを削除する。
  ※hさんの作成ファイルを利用するため、C:\instantrails\www\internal_management\ 以下すべて削除。

11.C:\instantrails\www\internal_management\ に 亀さん(subversion)でhさんのソースを持ってくる。

12.RadRails リフレッシュ。

13.RadRails で WEBrickサーバーを立ち上げる。ポートは3000。

14.エラーがでる。
   むむ・・・・。以下のようなエラーが出る。
************************************************
C:/InstantRails-1.3a-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/activesupport-1.3.1/lib/active_support/dependencies.rb:140:in `load': ./script/../config/../vendor/plugins/active_heart/lib/active_record_messages_ja.rb:30: parse error, unexpected tIDENTIFIER, expecting '}' (SyntaxError)
:invalid => "縺ッ荳肴ュ」縺ェ蛟、縺ァ縺?",
^
./script/../config/../vendor/plugins/active_heart/lib/active_record_messages_ja.rb:30: Invalid char `\257' in expression
./script/../config/../vendor/plugins/active_heart/lib/active_record_messages_ja.rb:30: Invalid char `\255' in expression




************************************************

どうも、文字コードがだめらしい・・・。

15.こちらを参考に文字コード設定。

  **********************
  $KCODEを設定する
  config/enviroment.rbの頭に
  $KCODE = 'u'
  **********************

たしかに、これで動いた・・・。でも、副作用がある模様。
$KCODEを指定することによりRailsのエラー画面で文字化けしなくなったり、正規表現で.がマルチバイト文字にマッチするようになる。
ただ正規表現マッチの挙動が変わるという副作用もあるので、そこのところを頭においておくべきだろう。(参考: http://arika.org/diary/20060201#p02 )

16.DBを作成する。
   コマンドプロンプトで以下のコマンドをたたく。
   ***********
   rake environment RAILS_ENV=development db_setup
   ***********

   これで、開発用のDBができる。

17.次に、
   ***********
   rake migrate
   ***********

むむ・・・。エラー。
   **************
   Lost connection to MySQL server during query
   **************

以下のコマンドを打つ。
   *************
   gem install mysql
   *************

もう一度、
   ***********
   rake migrate
   ***********

OK.
これで、DBにテーブルがセットされる。hさんありがとう。

ああ、環境設定は大変。。。
ちゃんと理解しないと・・・。

2006年10月25日

Railsでデバッグをする7つの方法

とりあえず、メモ。あとでじっくり検証。

http://rails.office.drecom.jp/takiuchi/archive/115

2006年10月31日

初心者運転

本日、H氏とペアプロを行いました。
半分は、DB設計のMTGでした。

MTG後、実際の作業です。

RailsのDB作成は、
rake を利用すると便利なので利用。

lib/tasks/db_setup.rake
↑このファイルを作成・記述

rake db_setup
↑これをコマンドプロンプトで実行

そうすると、DBができる。
ちなみに、
rake environment RAILS_ENV=test db_setup
↑を実行すると、テスト用のDBができる。

次に、テーブル(スキーマ)を作成します。
これも、rake を利用します。

まず、Radrails の Generators を利用して、migration します。

例) create_reports

そうすると、
db/migrate/001_create_reports.rb
ができるので、記述。

そしたら、
rake migrate
これで、テーブルができる。


本日は、僕がドライバーをしましたが、初心者運転です。
初心者マークがほしかったです。
H氏が教官になり、教わりながらドライブ。
自分で動かすと理解度が100倍です。
H氏ありがとうございます!

・・・ちゃんと自分で覚えないと・・・。
日々勉強です。

2006年11月14日

Linux に Ruby 、 Rails 、 Mysql をインストールしてアプリを動かす

※実行日は、2006年11月14日20:00前後

※以前インストールされていたrubyをアンインストール
# yum remove ruby
※ruby 1.8.5 をインストール
# cd /tmp
# wget ftp://ftp.ruby-lang.org/pub/ruby/ruby-1.8.5.tar.gz
# cd /usr/src/
# tar xzf /tmp/ruby-1.8.5.tar.gz
# cd ruby-1.8.5/
# ./configure
# make
# make test
test succeeded
# sudo make install
※rubyにパスを通す
# PATH=$PATH:/usr/src/ruby-1.8.5
# export PATH
※rubygems 0.9.0 インストール
# cd /tmp
# wget http://rubyforge.org/frs/download.php/11289/rubygems-0.9.0.tgz
# cd /usr/src/
# tar xzf /tmp/rubygems-0.9.0.tgz
# cd rubygems-0.9.0/
# sudo ruby setup.rb
# sudo gem install rails --include-dependencies
※パッケージインストール
# gem install mysql
# gem install json
※mysql インストール
# yum install mysql
※mysql スタート
# /etc/init.d/mysqld start
※再起動時に自動起動するように設定
# chkconfig --level 3 mysqld on
# chkconfig --level 5 mysqld on
※rails アプリケーション起動テスト
# cd /var
# mkdir rails_project
# cd rails_project
# rails demo
# cd demo
# ruby script/server
※http://localhost:3000/ が見れる事を確認。
※サブバージョンで管理されているファイルを持ってくる。
# cd /var/rails_project/
# svn checkout https://10.20.139.173/svn/tools/diary_report
※データベース作成
# mysql -u root
mysql> create database diary_report_development default character set utf8;
mysql> create database diary_report_test default character set utf8;
mysql> create database diary_report_production default character set utf8;
mysql> \q
※/var/rails_project/diary_report/config/database.yml に 「 socket: /var/lib/mysql/mysql.sock 」 を追記
# mysqladmin variables | grep socket
| socket | /var/lib/mysql/mysql.sock
※データベースのスキーマ作成
# rake migrate
※開発アプリケーションで起動(その前にテストアプリ終了する)
# ruby script/server
※その他、少し修正したが、エラーメッセージを見れば分かるので省略。

2006年12月27日

Ruby on Rails 各ディレクトリの役割

最近 Ruby on Railsから離れていたので、復習。

○各フォルダの役割

・app
アプリケーション本体、モデル・コントローラー・ビューなどを入れる。
app/models -> モデルのファイルを入れる
app/controllers -> コントローラーのファイルを入れる
app/views -> ビューのファイルを入れる
app/helpers -> ビューで使うヘルパーを入れる

・components
モデル、コントローラー、ビューをセットにしたコンポーネントと呼ばれるパーツを入れるディレクトリ

・config
設定ファイルを入れるディレクトリ。Ruby on Railsの環境設定、データベースの設定、URIとアプリケーションのマッピングの設定を行う。

・db
データベースの構造を記述するファイルを入れるディレクトリ。

・lib
アプリケーションで使うライブラリ

・public
HTTPサーバーのルートディレクトリにあたるディレクトリ。スタイルシート、JavaScript、画像ファイルなどの静的ファイルや、CGIを起動するためのファイルを置く。

・script
アプリケーションの作成支援するスクリプト群があるディレクトリ。

・test
テストの為のファイルを入れるディレクトリ。

・vendor
Ruby on Rails 自身のライブラリやプラグインなどを収めるディレクトリ。

・doc
ドキュメント

・log
ログファイル

データベース作成 と テーブル作成(migrate)

Ruby on Rails 復習。

○データベースの作成(例:MySQL)
create database [データベース名] default character set utf8;

[なんか名前]_development
[なんか名前]_test
[なんか名前]_production
↑この3つのデータベースを作る。

※ユーザー権限設定が必要であれば行う。
例:
grant all privileges on *.* to user_name@localhost identified by 'passwd' with grant option;

○migration -> データベースにテーブルを作成できる。データベース構造のバージョン管理もできる。
具体的に出来ること
* テーブルの作成・削除
* カラムの追加・削除・変更
* インデックスの追加・削除

○対応しているデータベース
* MySQL
* PostgreSQL
* Oracle
* SQLite

・ファイルの場所
db/migrate/○○.rb

・migration のヘルプの見方
 1.Railsアプリのあるディレクトリに移動する。
 2.ruby script/generate migration --help

・migration ファイルの作り方(Railsのトップディレクトリで)
ruby script/generate migration create_[テーブル名]

これで、 db/migrate/001_create_[テーブル名].rb というファイルができる。
テーブルひとつに対してひとつ。

- db/migrate/001_create_[テーブル名].rb - 修正前
{{{
class CreateBirthdayLists < ActiveRecord::Migration
def self.up
end

def self.down
end
end
]}}
- db/migrate/001_create_[テーブル名].rb - 修正後の例
{{{
class CreateBirthdayLists < ActiveRecord::Migration
def self.up
create_table(:birthday_lists) do |table|
table.column(:company_directory_no, :integer, :null => false)
table.column(:name, :string, :limit => '100', :null => false)
table.column(:birthday, :date)
end
end

def self.down
drop_table(:birthday_lists)
end
end
]}}

※idは自動的に作成される

・migration ファイルの説明
self.up : migration のバージョンがあがるときに実行される
sefl.down : migration のバージョンが下がるときに実行される

・rake db:migrate
migration ファイルを作成したら実行しましょう。テーブルが出来ます。


・参考
http://www.atmarkit.co.jp/im/carc/serial/proto04/proto04.html

Ruby on Rails 画面の雛形を作ろう

○scaffold 概要
scaffold(建築現場の足場) - あるテーブルを編集するためのモデル、ビュー、コントローラーの各雛形を作ってくれる。

○scaffold オプション
ruby script/generate scaffold --help
↑ヘルプで見ましょう

○scaffold 実行
例) ruby script/generate scaffold [モデル名]
※[モデル名]は大文字から始める。もし、テーブル名が report_lists だったら、モデル名は、Report_list です。

○scaffold で作成されるファイルの役割
app/models/report_list.rb  Report_list モデルを記述する。
app/views/report_lists/_form.rhtml  登録と編集で利用するビュー
app/views/report_lists/list.rhtml  一覧表示を行うビュー
app/views/report_lists/show.rhtml  詳細表示を行うビュー
app/views/report_lists/new.rhtml  登録画面のビュー
app/views/report_lists/edit.rhtml  編集画面のビュー
app/controllers/report_lists_controller.rb  コントローラ
test/functional/report_lists_contoroller_test.rb  コントローラのテストプログラム
app/helpers/report_lists_helper.rb  ヘルパープログラム
app/views/layouts/report_lists.rhtml  スケジュールコントローラのビューで利用する画面の共通部分のビュー
test/unit/report_list_test.rb  report_list モデルのテストプログラム
test/fixtures/report_lists.yml  report_list モデルのテストで使用するデータを記述するYAMLファイル
public/stylesheets/scaffold.css  スタイルシート

2006年12月28日

Ruby on Rails 画面の雛形を作ろう 続き

復習。

Ruby on Rails の動作のようす。


1. http://127.0.0.0:3000/birthday_lists/list.rhtml にアクセス。
2. app/controllers/birthday_lists_controller.rb に書かれている BirthdayListsController クラスの中の list という名前のアクションメソッドが呼ばれる。
3. 特に指定しないときはアクションメソッドと同名のビュー (app/views/schedules/list.rhtml) を表示する。

テストの内容を解読しよう

○コード例
------------------------------------------------------------
# Re-raise errors caught by the controller.
class BirthdayListsController; def rescue_action(e) raise e end; end

class BirthdayListsControllerTest < Test::Unit::TestCase
fixtures :birthday_lists

(略)

def test_list
get :list

assert_response :success
assert_template 'list'

assert_not_nil assigns(:birthday_lists)
end

(略)



------------------------------------------------------------

○get :list
 BirthdayListsController の list というアクションにGETアクセスする。

○assert_response :success
 レスポンスが成功 (HTTP の リザルトコードが200) になることを確認する。

○assert_template 'list'
 app/views/birthday_lists/list.rhtml が表示されることを確認する。

○assert_not_nil assigns(:birthday_lists)
 表示する際に代入されている @birthday_lists というインスタンス変数が nil でないことを確認する。

便利な paginate

○例
------------------------------------------------------
def list
@birthday_list_pages, @birthday_lists = paginate( :birthday_lists, :per_page => 10, :order => 'date DESC')
end
------------------------------------------------------

paginateの第一引数にはモデルの名前*1、第二引数には以下のようなオプションを指定できる。

class_name
モデルのクラス名
per_page
一ページあたりの行数
conditions
where句
order_by
order by句
join
join句
parameter
ページ番号を指定するためのパラメータの名前

参考
http://shugo.net/jit/20050422.html

Ruby on Rails 画面の雛形を作ろう 3

<%= render :partial => 'form' %>


render というのは、別のテンプレートをERBで解釈して返すメソッド。
partial は一部と言う意味で、:parial => 'form' と指定すると _form.rhtml をテンプレートとして使う。

partial で使うテンプレートのファイル名は先頭に『_』というのも、Ruby on Rails の規約のひとつ。

テストの内容を解読しよう 2

○コード例
---------------------------------------------------------
== テストコード一部抜粋(functionalより) ==
def test_create
num_birthday_lists = BirthdayList.count

post :create, :birthday_list => {}

assert_response :redirect
assert_redirected_to :action => 'list'

assert_equal num_birthday_lists + 1, BirthdayList.count
end
---------------------------------------------------------

○num_birthday_lists = BirthdayList.count
BirthdayListモデルのオブジェクトの数を num_birthday_lists に代入しておく。

○post :create, :birthday_list => {}
BirthdayListsCntroller の create というアクションに、空の params[:birthday_list] で POST アクセスする。

○assert_response :redirect
レスポンスがリダイレクト( HTTPのリザルトコードが302 )になることを確認する。

○assert_redirected_to :action => 'list'
BirthdayListsCntroller の list というアクションにリダイレクトされることを確認する。

○assert_equal num_birthday_lists + 1, BirthdayList.count
BirthdayListモデルのオブジェクトの数は1増えていることを確認する。

2007年01月18日

Ruby on Rails マニュアル

api_ruby.jpg

http://api.rubyonrails.org/

2007年01月19日

RailsCronプラグイン

h氏にRails で cron が使えるプラグイン教えていただいたのでメモ。

http://rails.office.drecom.jp/takiuchi/archive/55

rails CSV形式のファイル処理プラグイン

rails CSV形式のファイル処理プラグイン

http://www.gesource.jp/programming/ruby/database/fastercsv.html

Rails1.2 目玉機能>ActiveResource

Ruby on Rails 1.2 が出た。

○ruby on rails
http://www.rubyonrails.org/

○ActiveResourceが目玉機能らしい>rails1.2
http://d.hatena.ne.jp/keyword/ActiveResource
http://cesare.seesaa.net/article/19567455.html

○既存の機能ももちろん進化
http://subtech.g.hatena.ne.jp/secondlife/20061222/1166765090

:以下引用
-------------------------
start_form_tag, end_form_tag を使うと警告ができるようなりました。代わりに form_tag, を使いましょう
-------------------------

これは は使わずに
-------------------------
form_tag do
end
-------------------------
と form_tag にブロックを渡す方法が正しいかと。それと

-------------------------
scrpit/server は Rails 1.1 では WEBrick を起動し
-------------------------
ですが、実際に Rails 1.1 では lighttpd, webrick の順番で起動されます。1.2 からは mongrel があると mongrel が最優先になる変更、ですね。

2007年03月27日

CruiseControl.rb

継続的インテグレーションを行うツール。

○継続的インテグレーション
http://www.objectclub.jp/community/XP-jp/xp_relate/cont-j


http://cruisecontrolrb.thoughtworks.com/
http://www.martinfowler.com/articles/continuousIntegration.html#MaintainASingleSourceRepository.
http://d.hatena.ne.jp/kstn/20070314/1173854051

2007年03月29日

AR 便利機能 created_on updated_on

:created_on という名前のカラムがあれば、エントリの作成時に時刻が入る。
:updated_on という名前のカラムがあれば、エントリ更新時に時刻が入る。


便利だなぁ。

2007年04月12日

Ruby On Railsのクラスを解析してダイアグラムにしてくれる『Rails Road』

おおおおぉぉ

http://www.popxpop.com/archives/2007/04/ruby_on_railsrails_road.html

http://railroad.rubyforge.org/

使い方とか
http://blog.takeda-soft.jp/blog/show/157

2007年04月19日

Ruby on Rails : テーブル間リレーションシップ

モデルでテーブル間のリレーションを宣言するときの注意。

>ややこしいのが参照先テーブル名の指定で、 belongs_to と has_one では単数形、 has_many と has_many_and_belongs_to では複数形で記述しなければなりません。


リレーションは、最初ややこしい...。


http://webos-goodies.jp/archives/50773406.html

2007年04月27日

rails 特定のバージョンを指定してインストール

gem install rails --version 1.1.6 --include-dependencies

↑コンナ感じ。

2007年05月01日

rails を mongrel で動かす

1.まず、rails をどのような環境で動かすか考える。
――――――――――――――――――――――――――――――――――――――――
DBはMySQLで決まり。

うーん。Webサーバーが問題だ。

Webサーバーを何にするか、
そのWebサーバーでどうやってrailsを動かすか調べないといけない。
railsを本番で動かすのって、
みんなどうやってるんだ?

apache?righttpd?Mongrel?

とりあえず、「rails apache」「rails Mongrel」「rails righttpd」「rails 本番環境」でググって見る。

「rails apache」でググったところ、くまくまーさんのエントリーで以下のようなものが!
http://wota.jp/ac/?date=20060605
これによると、
「Mongrel」が「速い上にWEBrick互換のオプションがある。Rails 濃い人は lighty から乗り換え中」
と書いてある。

Mongrelか?


2.Mongrelを調べる
――――――――――――――――――――――――――――――――――――――――
「Mongrel rails」でググって見る。


○MongrelでRailsを動かしてみる。
http://www.fraction.jp/log/archives/2006/09/1020
[root@emma ~]# gem install mongrel
○Nginx + Mongrel という選択肢
http://wota.jp/ac/?date=20060823


・・・色々見てみるが決定打なし...。

とりあえず、Mongrelでやってみるか...。


新サーバーの設置しなきゃ・・・。


3.CentOS5をダウンロード
――――――――――――――――――――――――――――――――――――――――
まず、CentOS5をダウンロード!
http://www.centos.org/


4.CDに焼く by burnatonce
――――――――――――――――――――――――――――――――――――――――

ダウンロードした6つのファイルをCDに焼きます。


5.CentOS5をインストール
――――――――――――――――――――――――――――――――――――――――
※CDを一番最初に起動するようにする
※ruby,mysqlにチェックを忘れずに!

いざ、サーバーにインストール!


5.rubyの確認
――――――――――――――――――――――――――――――――――――――――
ruby -v


6.checkinstallのinstall
――――――――――――――――――――――――――――――――――――――――
http://centos.oss.sc/fundamentals/checkinstall/


7.rubygemsのinstall
――――――――――――――――――――――――――――――――――――――――
http://centos.oss.sc/ruby/gems/
http://webrec.jp/blog/?tag=ruby
0.8.11 だと成功する...。


8.rails1.1.6のインストール
――――――――――――――――――――――――――――――――――――――――
gem install rails --version 1.1.6 --include-dependencies


9.rails確認
――――――――――――――――――――――――――――――――――――――――
rails -v
参考:
http://d.hatena.ne.jp/kabus/20070225
http://www.rubyonrails.org/


10.Mongrelのインストール
――――――――――――――――――――――――――――――――――――――――
gem install mongrel
>1 #1. mongrel 1.0.1 (ruby) を選択した。
Install required dependency daemons? [Yn] Y
>1 #1. fastthread 1.0 (ruby)
Install required dependency gem_plugin? [Yn] Y

参考:
http://www.fkino.net/hiki/?MongrelInstall (Linux)
http://rihi.cocolog-nifty.com/blog/2006/11/radrails_1327.html (Windows)


なんか、成功したっぽい。


11.Mongrelを起動してみる。
――――――――――――――――――――――――――――――――――――――――
[root@localhost ~]# mongrel_rails start
!!! Path to log file not valid: log/mongrel.log
mongrel::start reported an error. Use mongrel_rails mongrel::start -h to get help.


なんか、怒られた。何がいかんのんか...。
「Mongrel start」でググって見よう。


うーん。どうも、railsアプリのフォルダに移動して実行するらしい。
WEBrickに似てるのか?

とりあえず、railsアプリのある場所で起動してみる。

[root@localhost ~]# cd /srv/www/lighttpd/lr_portal/
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.


む!さっきと反応が違うぞ!

http://10.20.138.111:3000
でアクセスしてみる。

おおおおぉ。railsのお馴染みの画面が表示された!


それにしても、righttpd のフォルダなんですが・・・。
まぁいいか...。


11.Mongrelでrailsの本番環境のDB(production)を使うにはどうすればいいのか。
――――――――――――――――――――――――――――――――――――――――
とりあえず、mysqlにログインしてみる。

[root@localhost ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>


おおおおぉ。あっさりログイン。
server version: 5.0.22 か...まぁ、問題ないな...。


mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
+--------------------+
3 rows in set (0.00 sec)


まぁ、DBがひとつもないのは、当たり前。


さっそくDB作るか。


・・・あ、そういえば。

railsには、本番用と開発用のサーバーがあったな。
いつも、開発用使ってるけど、本番用を使うにはどうするんだ?
そもそも、development から production にどうやって変更するんだ...。
railsの設定なんだろうな・・・。

ちょっとググって見よう。
「rails production 設定」

こんなの見つける。
http://rails.office.drecom.jp/hibi/archive/12

>P462を見る。
>各Webサーバによってproductionの指定が違うみたい。
>お手軽にWEBrickでやるとき。コマンドプロンプトで。

>C:\Program Files\ruby\rails_apps\your_app>set rails_env=production
>C:\Program Files\ruby\rails_apps\your_app>ruby script\server --environment=production

>としたらおっけー!
>へぇ、まじで!簡単だ。
>あ、もちろん、database.ymlでproductionのDBを設定しとくの忘れないでね。

うーむ。WEBrickでやるときか...。

「rails production mongrel」でググってみよう。

こんなの見つける。
http://d.hatena.ne.jp/catalina/20060922
> mongrel_rails start -d -p 3000 -e production

とりあえず、コンナ感じでよいと思うので、とりあえず次に進む。


12.DBを作成する
――――――――――――――――――――――――――――――――――――――――
これでよいのか...。とりあえず、DB作ろう。
あ、本番は、productionだけでいいのか。

# create database lr_portal_production default character set utf8;


12.DBへのアクセス権限設定
――――――――――――――――――――――――――――――――――――――――
次に、権限を設定。

grant all privileges on lr_portal_production.* to fukushige@localhost identified by 'fuku' with grant option;


13.アプリケーションをアップロード
――――――――――――――――――――――――――――――――――――――――
SSHで接続して、ローカルで作ったやつを無理やり
/srv/www/lighttpd/lr_portal/
に root でアップロードしてみる。


14.migrate
――――――――――――――――――――――――――――――――――――――――
データベースにテーブルを作成する。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
No such file or directory - /tmp/mysql.sock

(See full trace by running task with --trace)


むあ!なんか怒られた。

「No such file or directory - /tmp/mysql.sock」でググって見る。


http://cyclon.s11.xrea.com/mt/archives/2005/11/ruby_on_rails_m.html
↑こんなサイト見つける。

これによると、
>MySQL で接続のために生成している UNIX socket のファイルが /tmp/mysql.sock にないために発生しています。 MySQL は default でこのパスにファイルを生成しますが、設定によって変更されている場合があります。この場合、明示的に設定してあげる必要があります。

と書いてある。
解決方法まで書いてある。

>1. MySQL が UNIX socket をどこに生成しているかを確認
>mysqladmin variables | grep socket
>2. config/database.yml のデータベース設定の 1 つとして UNIX socket のパスを追記(データベース名やユーザー名と同様に記述すればよい)、以下 "/var/lib/mysql/mysql.sock" だった場合の例
>3.socket: /var/lib/mysql/mysql.sock
>4. WEBrick を再起動


とりあえず、やってみる。


まず、1

[root@localhost lr_portal]# mysqladmin variables | grep socket
| socket | /var/lib/mysql/mysql.sock

どうやら、 /var/lib/mysql/mysql.sock にあるらしい。

それで、2と3
/config/database.yml のproduction に socket: /var/lib/mysql/mysql.sock を追加した。

それで、再びアップロード。


ふたたびやってみる。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
No such file or directory - /tmp/mysql.sock

(See full trace by running task with --trace)


むああ!同じだ。

developmentにもやらないとダメなのか...?
いや、利用するのは production にしたいのだから...。
先に、mongrel を production モードで立ち上げないといけないのか?

とりあえず、やってみる。


[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start -d -p 3000 -e production


これで、http://10.20.138.111:3000 を見てみると・・・。
あ!!ログイン画面登場!!!
なるほど!
DBに接続した!!


では、テーブルを作成する。

[root@localhost lr_portal]# rake db:migrate

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
No such file or directory - /tmp/mysql.sock

(See full trace by running task with --trace)
[root@localhost lr_portal]#

ああああ!失敗・・・。

むー。

config/database.ymlの
development と test にも socket: /var/lib/mysql/mysql.sock を追加してみよう。

追加して・アップ。mongrel再起動。
[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start -d -p 3000 -e production

でやってみる。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)
[root@localhost lr_portal]#

むあああー!なんか違うエラーでた。

なんか、 schema_info がなんちゃらと言っている...。


うーん。もしかして、 development みてるのか・・・。

とりあえず、development と test のDB作って、権限与えてみよう。

create database lr_portal_development default character set utf8;
create database lr_portal_test default character set utf8;
grant all privileges on lr_portal_development.* to fukushige@localhost identified by 'fuku' with grant option;
grant all privileges on lr_portal_test.* to fukushige@localhost identified by 'fuku' with grant option;


でやってみる。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


むあああああー!同じエラー出た。
ちゃんとエラーメッセージ読もう。

どうも、SELECT version FROM schema_info にアクセスできないらしい。
当たり前である。ないし。

ああああ、ローカルでは前に、db:migrate しているから、バージョンを読もうとしているのか。
バージョン指定して、やってみるか。

[root@localhost lr_portal]# rake migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


むあああ!おなじだあぁl!

つーか。開発では、schema_info というテーブルはどうなっているんだ...?

と言うことで、ローカルのDBのdevelopmentのDBを見てみる。

mysql> use lr_portal_development
Database changed
mysql> select * from schema_info
-> ;
+---------+
| version |
+---------+
| 14 |
+---------+
1 row in set (0.02 sec)


うーむ。なるほど。
手で作ってみるか。


mysql> CREATE TABLE schema_info
-> (
-> version INT NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)

insert into schma_info (version) values (14);


mysql> select * from schema_info;
+---------+
| version |
+---------+
| 14 |
+---------+
1 row in set (0.00 sec)


これでやってみる。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)
[root@localhost lr_portal]# rake db:migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)
[root@localhost lr_portal]#


むがあああぁ!変わらないし!
あ、production の方に作ってみよう。


mysql> use lr_portal_production
Database changed
mysql> CREATE TABLE schema_info ( version INT NOT NULL );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into schema_info (version) values (14);
Query OK, 1 row affected (0.00 sec)

これでやってみる。

[root@localhost lr_portal]# rake db:migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info
(See full trace by running task with --trace)
[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info
(See full trace by running task with --trace)


むおおおお。変わらん・・・。


なんなの・・・?

http://d.hatena.ne.jp/kabus/20061005
む、↑で見ると、権限の設定らしいぞ。
あれ?設定したのになぁ...。
もう一度見てみよう。


あ・・・
gem install mysql
やってないかも・・・。

[root@localhost lr_portal]# gem install mysql
Attempting local installation of 'mysql'
Local gem file not found: mysql*.gem
Attempting remote installation of 'mysql'
Select which gem to install for your platform (i386-linux)
1. mysql 2.7.3 (mswin32)
2. mysql 2.7.1 (mswin32)
3. mysql 2.7 (ruby)
4. mysql 2.6 (ruby)
5. mysql 2.5.1 (ruby)
6. Cancel installation
> 3
Building native extensions. This could take a while...
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/bin/ruby
--with-mysql-config
--without-mysql-config
--with-mysql-dir
--without-mysql-dir
--with-mysql-include
--without-mysql-include=${mysql-dir}/include
--with-mysql-lib
--without-mysql-lib=${mysql-dir}/lib
--with-mysqlclientlib
--without-mysqlclientlib
--with-mlib
--without-mlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-zlib
--without-zlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-socketlib
--without-socketlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-nsllib
--without-nsllib
--with-mysqlclientlib
--without-mysqlclientlib
ERROR: While executing gem ... (RuntimeError)
ERROR: Failed to build gem native extension.
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.7 for inspection.
ruby extconf.rb install mysql\nchecking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no


Results logged to /usr/lib/ruby/gems/1.8/gems/mysql-2.7/gem_make.out
[root@localhost lr_portal]#

うううん。
なんか、Error出てる...。

http://rubyist.g.hatena.ne.jp/pulscope/20070201
↑ここで書いてある方法をやったら、とりあえずインストールできた。


[root@localhost lr_portal]# sudo gem install mysql -- --with-mysql-lib=/usr/lib/mysql
Attempting local installation of 'mysql'
Local gem file not found: mysql*.gem
Attempting remote installation of 'mysql'
Select which gem to install for your platform (i386-linux)
1. mysql 2.7.3 (mswin32)
2. mysql 2.7.1 (mswin32)
3. mysql 2.7 (ruby)
4. mysql 2.6 (ruby)
5. mysql 2.5.1 (ruby)
6. Cancel installation
> 3
Building native extensions. This could take a while...
mysql.c: In function ‘make_field_obj’:
mysql.c:185: 警告: unused variable ‘hash’
mysql.c: In function ‘stmt_execute’:
mysql.c:1316: 警告: unused variable ‘false’
mysql.c: In function ‘time_initialize’:
mysql.c:1703: 警告: control reaches end of non-void function
mysql.c: In function ‘stmt_execute’:
mysql.c:1365: 警告: ‘t.time_type’ is used uninitialized in this function
mysql.c:1378: 警告: ‘t.time_type’ is used uninitialized in this function
ruby extconf.rb install mysql -- --with-mysql-lib=/usr/lib/mysql
checking for mysql_query() in -lmysqlclient... yes
checking for mysql_ssl_set()... yes
checking for mysql.h... no
checking for mysql/mysql.h... yes
creating Makefile

make
gcc -I. -I. -I/usr/lib/ruby/1.8/i386-linux -I. -DHAVE_MYSQL_SSL_SET -DHAVE_MYSQL_MYSQL_H -I/usr/local/include -fPIC -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -Wall -fPIC -c mysql.c
gcc -shared -L"/usr/lib/mysql" -L"/usr/local/lib" -L"/usr/lib" -o mysql.so mysql.o -lruby -lmysqlclient -lpthread -ldl -lcrypt -lm -lc

make install
mkdir -p /usr/lib/ruby/gems/1.8/gems/mysql-2.7/lib
/usr/bin/install -c -m 0755 mysql.so /usr/lib/ruby/gems/1.8/gems/mysql-2.7/lib
Successfully installed mysql-2.7


で、migrate やってみる。

[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


ぐはーー。
エラー出る。


とりあえず、mongrel 再起動してみる。

[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start -d -p 3000 -e production


[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


あかん・・・。


そもそも、
Mysql::Error: Lost connection to MySQL server during query
の意味は、なんなんだ?
と言うことで、調べてみる。

「Mysql::Error: Lost connection to MySQL server during query」ググって見る。


http://d.hatena.ne.jp/coolstyle/comment?date=20061226
>ログ
>Mysql::Error: Lost connection to MySQL server during query
>Googleで調べた限りでは「gem install mysql」すれば良いらしいと書かれてあったので、DBサーバー側のDebianで必死にコマンドを打っていたのだけど一向に正常に動かない。
>何がいけないのか全くわからなかったのだが、原因はいたって単純だった。
>結局、「gem install mysql」しなければいけないのはサーバー側ではなく、クライアント側だったのである。

はぁ...クライアント側?


[root@localhost lr_portal]# rake db_schema_dump
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SHOW TABLES

(See full trace by running task with --trace)
[root@localhost lr_portal]#


権限をもう一度、やってみる。
grant all privileges on *.* to fukushige@localhost identified by 'fuku' with grant option;

・・・あかん・・・。


http://rails.office.drecom.jp/q1w2e3r4/daily/200606/30
↑これ発見。

yum install mysql-devel

やってみる。インストール成功。

[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


むーん。あかん。


config/database.yml

username: fukushige
password: fuku

username: root
password:
にしてみる。

[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)

あ、エラーが出ない。
どうも。権限らしい・・・。


[root@localhost lr_portal]# rake migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
== CreateReportsAuthentications: reverting ====================================
-- drop_table(:reports_authentications)
rake aborted!
Mysql::Error: #42S02Unknown table 'reports_authentications': DROP TABLE reports_authentications

(See full trace by running task with --trace)


むーー。今度は、なんだ・・・。
あー。なるほど。


lr_portal_development の schema_info を 0 にする。

use lr_portal_development
update schema_info set version=0;

コレで、


[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
== CreateUnits: migrating =====================================================
-- create_table(:units)
-> 0.0110s
== CreateUnits: migrated (0.0116s) ============================================

== CreatePositions: migrating =================================================
-- create_table(:positions)
-> 0.0050s
== CreatePositions: migrated (0.0056s) ========================================

== CreateWorkForms: migrating =================================================
-- create_table(:work_forms)
-> 0.0044s
== CreateWorkForms: migrated (0.0049s) ========================================

== CreateUserAuthorizations: migrating ========================================
-- create_table(:user_authorizations)
-> 0.0142s
== CreateUserAuthorizations: migrated (0.0147s) ===============================

== CreateCompanyDirectories: migrating ========================================
-- create_table(:company_directories)
-> 0.0081s
== CreateCompanyDirectories: migrated (0.0087s) ===============================

== CreateUsers: migrating =====================================================
-- create_table(:Users)
-> 0.0047s
== CreateUsers: migrated (0.0053s) ============================================

== CreateChangeLogs: migrating ================================================
-- create_table(:change_logs)
-> 0.0051s
== CreateChangeLogs: migrated (0.0057s) =======================================

== CreateAuthentications: migrating ===========================================
-- create_table(:authentications)
-> 0.0264s
== CreateAuthentications: migrated (0.0270s) ==================================

== CreateAuthResponses: migrating =============================================
-- create_table(:auth_responses)
-> 0.0048s
== CreateAuthResponses: migrated (0.0054s) ====================================

== CreateReports: migrating ===================================================
-- create_table(:reports)
-> 0.0061s
== CreateReports: migrated (0.0067s) ==========================================

== CreateComments: migrating ==================================================
-- create_table(:comments)
-> 0.0051s
== CreateComments: migrated (0.0057s) =========================================

== CreateReportTypes: migrating ===============================================
-- create_table(:report_types)
-> 0.0045s
== CreateReportTypes: migrated (0.0051s) ======================================

== CreateReportsAuthentications: migrating ====================================
-- create_table(:reports_authentications)
-> 0.0043s
== CreateReportsAuthentications: migrated (0.0048s) ===========================

[root@localhost lr_portal]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 41 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

おおおぉ。成功!


15.railsへのアクセス
――――――――――――――――――――――――――――――――――――――――
これで、

http://10.20.138.111:3000/account/su_login

にアクセスしてみる。

おおおおぉ。画面が表示される!

スーパーユーザでログイン!
※DBを見ない、ログインなので、ログインできるはず!!

で、やってみる。

Application error (Rails)

↑画面にコレが表示される・・・。

コレはいったい・・・。

あー。ファイルの権限の問題か・・・。

うーむ
app/controllers
app/helpers
app/models
app/views
のファイルをすべて 777 にしても表示されない・・・。


「Application error (Rails)」でググって見る。


http://pools.jp/2006/05/09/rails-webrick-application-error/
↑ここによると、


>これはWEBrickの起動時のカレントディレクトリが問題で、例えば、
> $rails demo
>でdemoアプリを作成した際には、
> $cd demo
>として作成したアプリのディレクトリに移動してから
> $ruby script/server
>としてWEBrickを起動すればApplication error (Rails)にはならず、実行環境が表示される。
>しょうもないエラーでした。

はぁ・・・でも、
/srv/www/lighttpd/lr_portal/
で mongrel 起動してるしなぁ・・・。

あ、、

[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start
(前は、⇒# mongrel_rails start -d -p 3000 -e production だった)

これで、start したら、
Application error (Rails)
はでなくなったが・・・。

MissingSourceFile
no such file to load -- fastercsv
が出る。

gem install fastercsv
やると・・・。
[root@localhost lr_portal]# gem install fastercsv
Attempting local installation of 'fastercsv'
ERROR: Error installing gem fastercsv[.gem]: undefined method `include?' for nil:NilClass


うーむ・・・なんだろう。。

[root@localhost lr_portal]# cd /opt/
[root@localhost opt]# gem install fastercsv
Attempting local installation of 'fastercsv'
Local gem file not found: fastercsv*.gem
Attempting remote installation of 'fastercsv'
Updating Gem source index for: http://gems.rubyforge.org
Successfully installed fastercsv-1.2.0
Installing RDoc documentation for fastercsv-1.2.0...

場所変えたら、成功した・・・。なぜ・・・。


これで、

http://10.20.138.111:3000/ にアクセスすると!!

見れました!!!!

よし!!!
ちゃんと mysql とも連動してる!


16.課題点
――――――――――――――――――――――――――――――――――――――――
でも、以下の課題点がある。?

1.config/database.yml で利用している mysql のユーザーが root である。しかもパスワードなし。(ユーザー作って解決?)
2.development で動いている、production で動かさないとな。


とりあえず、これが解決できればいいカナと思う。
明日やろ。

続きはこちら

2007年05月02日

rails を mongrel で動かす 2

前回の続き。

17.課題点の解決
――――――――――――――――――――――――――――――――――――――――
1.config/database.yml で利用している mysql のユーザーが root である。しかもパスワードなし。(ユーザー作って解決?)
2.development で動いている、production で動かさないとな。


昨日、上記2点の問題点があった。
解決しよう!おう!


18.config/database.yml で利用している mysql のユーザーが root である。しかもパスワードなし。
――――――――――――――――――――――――――――――――――――――――
これは、解決しないと・・・。
と言うか、そもそも、rootにパスワードがないのは、どうなんだ!
と言うことで、まずrootのパスワード保護からやろう。


とりあえず、mongrelを起動して現状をチェック。


SSHを利用してrootでログイン。
[root@localhost ~]# cd /srv/www/lighttpd/lr_portal/
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.


これで、http://10.20.138.111:3000/ にアクセスしてみる。

うむ。ちゃんと動いている。

では、mysqlのrootユーザーにパスワードをつけよう。

「mysql root パスワード」でググって見る。

http://www.rfs.jp/server/mysql/02/01.html
↑ここに書いてあった。

[root@localhost ~]# mysql -u root mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 47 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> SET PASSWORD FOR root=PASSWORD('********');
ERROR 1133 (42000): Can't find any matching row in the user table
mysql>

注意:******** ←ここは、ちゃんと入力してますからね。

ぐはー。なんかエラーでた。
ERROR 1133 (42000): Can't find any matching row in the user table
なんか、user table がないみたい?


「ERROR 1133 (42000): Can't find any matching row in the user table」でググって見る。

http://kajuhome.com/cgi-bin/patio/patio.cgi?mode=view&no=273
↑このページ。ようするに、利用するDBを選択してないからだと書いてある。

やってみる。

mysql> use mysql;
Database changed
mysql> SET PASSWORD FOR root=PASSWORD('********');
ERROR 1133 (42000): Can't find any matching row in the user table
mysql>

注意:******** ←ここは、ちゃんと入力してますからね。

ぐはあぁぁー。だめぢゃん。

あ、同じページに

>パスワードの設定は、ユーザの後にホスト名を追加しなければならないようです。
>以下の様に、「ユーザ@ホスト」の様に指定してください。
>mysql> SET PASSWORD FOR root@localhost=PASSWORD('abcde');

なるほど。やってみよう。


mysql> use mysql;
Database changed
mysql> SET PASSWORD FOR root@localhost=PASSWORD('*******');
Query OK, 0 rows affected (0.00 sec)

注意:******** ←ここは、ちゃんと入力してますからね。


やった!成功!!!


これで、http://10.20.138.111:3000/ にアクセスして、
色々いじってみる。エラーが出るはず。

あれ?
めちゃめちゃ登録できるし・・・。

mongrelを再起動してみる。

[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.


これで、http://10.20.138.111:3000/ にアクセスしてみる。

ビンゴ!

#28000Access denied for user 'root'@'localhost' (using password: NO)

パスワードがないって言うエラーが出た。

では、rails側でパスワードを設定してみる。

config/database.yml に設定したパスワードを設定して、アップロード。

あれ?同じ画面だ・・・。
mongrelを再起動してみる。


Mysql::Error: Lost connection to MySQL server during query: SHOW FIELDS FROM company_directories

ぬおおおぉ。
なんか、違うエラーが出た!!!

なんか、コネクションエラーっぽ・・・。
このエラー昨日もでなかったけ・・・?

このエラーはrailsからmysqlに接続するさいの認証のエラーだったはず・・・。
あ、

grant all privileges on *.* to fukushige@localhost identified by 'fuku' with grant option;

↑これやんなきゃだめなのか?
やってみよう。

[root@localhost lr_portal]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 58 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> grant all privileges on *.* to root@localhost identified by '*********' with grant option;
Query OK, 0 rows affected (0.00 sec)

mysql>

ついでに、mongrel再起動。

[root@localhost lr_portal]# mongrel_rails stop
[root@localhost lr_portal]# mongrel_rails start

これで、アクセスしてみる。

Mysql::Error: Lost connection to MySQL server during query: SHOW FIELDS FROM company_directories

むあぁ。おなじだ!!!

mysql を再起動してみよう。
その後、mongrelも再起動。


[root@localhost lr_portal]# /etc/init.d/mysqld restart
MySQL を停止中: [ OK ]
MySQL を起動中: [ OK ]
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.

で、アクセスしてみる。

Mysql::Error: Lost connection to MySQL server during query: SHOW FIELDS FROM company_directories

ぐはー。変わらん・・・。
DBへのアクセスエラーだな・・・。

もちつけ、もちつくんだ・・・。


[root@localhost lr_portal]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 16 to server version: 5.0.22

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> grant all privileges on lr_portal_production.* to root@localhost identified by '**********' with grant option;
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on lr_portal_test.* to root@localhost identified by '**********' with grant option;
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on lr_portal_development.* to root@localhost identified by '**********' with grant option;
Query OK, 0 rows affected (0.00 sec)

mysql>


上記のように権限を設定してみる。

mysql再起動。
mongrel再起動。

[root@localhost lr_portal]# /etc/init.d/mysqld restart
MySQL を停止中: [ OK ]
MySQL を起動中: [ OK ]
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.


で、アクセスしてみる。

Mysql::Error: Lost connection to MySQL server during query:


むむーん。変わらん・・・。何なの??


rootだからダメなのかな?

他のユーザを設定してみてやってみるか。

昨日
grant all privileges on lr_portal_production.* to fukushige@localhost identified by '****' with grant option;
grant all privileges on lr_portal_development.* to fukushige@localhost identified by '****' with grant option;
grant all privileges on lr_portal_test.* to fukushige@localhost identified by '****' with grant option;

とやっていたので、

database.yml の内容を

username: fukushige
password: fuku

にしてみる。

アップ、mysql,mongrel 再起動。
で、見てみる。

Mysql::Error: Lost connection to MySQL server during query:

ぐはぁぁあぁー!変わらん。
関係ないか・・・?

もっと、基本に返ろう。
railsの入門書を見てみよう。

config/database.yml で文字コードを指定していなかったので、指定してみる。

encoding: utf8

ついでに、config/environment.rb の一番上に $KCODE = "UTF8" を加えてみる。

次に、本に、rails と言うユーザーを作成しますと書いてあるが・・・これは必須??
とりあえず、作ってみる。

mysql> grant usage on *.* to rails@localhost identified by 'rails_rails';
Query OK, 0 rows affected (0.00 sec)

[root@localhost lr_portal]# /etc/init.d/mysqld restart
MySQL を停止中: [ OK ]
MySQL を起動中: [ OK ]
[root@localhost lr_portal]# mongrel_rails start


む、なんかエラーが変わった。

Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'


「SET NAMES 'utf8'」でググって見る。

http://phpspot.net/php/pgMySQL4.1%8CnUTF-8%82%CC%8F%EA%8D%87.html
↑に

>MySQL4.1系ではデフォルトでUTF-8文字列が使われます。
>PHPから普通にデータ挿入をしようとすると、文字化けします。
>SQL文を発行するまえに、クライアントの文字コード設定をしましょう。
>文字コードの設定は次の構文で行います。

>UTF8に設定するには次のSQL文を実行します。
>mysql> SET NAMES utf8;


とりあえず、やってみるか。


mysql> SET NAMES utf8;
Query OK, 0 rows affected (0.00 sec)

で、mysql,mongrel再起動。


[root@localhost lr_portal]# /etc/init.d/mysqld restart
MySQL を停止中: [ OK ]
MySQL を起動中: [ OK ]
[root@localhost lr_portal]# mongrel_rails start

で、見てみる。

Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'

変わらん・・。なんだろう・・・。

もう一度、
「Mysql Error Lost connection to MySQL server during query: SET NAMES utf8」でググって見る。

http://itpro.nikkeibp.co.jp/article/COLUMN/20060424/236113/?ST=lin-server&P=3
↑このページだと、
GRANT ALL PRIVILEGES ON addressbook.* TO ab@localhost IDENTIFIED BY 'ab';
やってるので、応用でやってみる。

GRANT ALL PRIVILEGES ON lr_portal_development.* TO rails@localhost IDENTIFIED BY 'rails_rails';
GRANT ALL PRIVILEGES ON lr_portal_test.* TO rails@localhost IDENTIFIED BY 'rails_rails';
GRANT ALL PRIVILEGES ON lr_portal_production.* TO rails@localhost IDENTIFIED BY 'rails_rails';

で、mysql,mongrel再起動。

※config/database.yml は
adapter: mysql
database: lr_portal_development
username: rails
password: rails_rails
encoding: utf8
host: localhost
socket: /var/lib/mysql/mysql.sock
↑な感じです。

[root@localhost lr_portal]# /etc/init.d/mysqld restart
MySQL を停止中: [ OK ]
MySQL を起動中: [ OK ]
[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.

で、見てみる。

Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'

変わらん・・・。むごー。

http://blogs.dion.ne.jp/koko/archives/4345309.html#more
mysqlの設定ファイルを発見。

/etc/my.cnf


http://d.hatena.ne.jp/shingotada/searchdiary?word=*[linux]
↑のページに、
>rubyのヘッダーをインストールしていない
と書いてある・・・。
rubyのヘッダー?

yum install ruby-devel

[root@localhost lr_portal]# yum install ruby-devel
Loading "installonlyn" plugin
Loading "fastestmirror" plugin
Loading "priorities" plugin
Setting up Install Process
Setting up repositories
Loading mirror speeds from cached hostfile
Reading repository metadata in from local files
0 packages excluded due to repository priority protections
Parsing package install arguments
Nothing to do

うまくいかない・・・。パッケージがない??


「ruby-devel Nothing to do」でググって見る。

・・・よくわからん・・・。

http://l5web.laser5.co.jp/rpm2html/7.2exp/ruby-devel-1.6.4-2.i386.html
↑このページにrpmがあったので、ダウンロード、インストールしてみる。

[root@localhost opt]# rpm -i ruby-devel-1.6.4-2.i386.rpm
エラー: 依存性の欠如:
ruby = 1.6.4-2 は ruby-devel-1.6.4-2.i386 に必要とされています

はぁ・・・。依存性の欠如?

わけわからんので、違う方法を検討する。
最初に戻ろう。


現状把握。


[root@localhost lr_portal]# mongrel_rails start
** Starting Mongrel listening at 0.0.0.0:3000
** Starting Rails with development environment...
** Rails loaded.
** Loading any Rails specific GemPlugins
** Signals ready. TERM => stop. USR2 => restart. INT => stop (no restart).
** Rails signals registered. HUP => reload (without restart). It might not work well.
** Mongrel available at 0.0.0.0:3000
** Use CTRL-C to stop.

mongrelスタートさせて、http://10.20.138.111:3000/ を見ると。

Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'

こうなる。
エラーメッセージは、接続がおかしいと言っている。
SET NAMES 'utf8' がなぞだ。
文字コードはutf8でDBもrailsも作っているのに・・・。
config/database.yml も config/environment.rb もutf8の設定にしてある。
うーん。


おもむろに、
「SET NAMES utf8 mysql rails」
とググって見る。


http://wota.jp/ac/?date=20061011
↑このページを見つける。


mysql> status
--------------
mysql Ver 14.12 Distrib 5.0.22, for redhat-linux-gnu (i686) using readline 5.0

Connection id: 9
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.0.22
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/lib/mysql/mysql.sock
Uptime: 2 hours 53 min 25 sec

Threads: 1 Questions: 4 Slow queries: 0 Opens: 0 Flush tables: 1 Open tables: 6 Queries per second avg: 0.000
--------------

mysql> show variables like "char%";
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)


mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)


↑これをやると。


mysql> status
--------------
mysql Ver 14.12 Distrib 5.0.22, for redhat-linux-gnu (i686) using readline 5.0

Connection id: 9
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.0.22
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /var/lib/mysql/mysql.sock
Uptime: 2 hours 54 min 51 sec

Threads: 1 Questions: 10 Slow queries: 0 Opens: 0 Flush tables: 1 Open tables: 6 Queries per second avg: 0.001
--------------

mysql> show variables like "char%";
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

utf8の部分が増える。


>/etc/my.cnf の設定
>MySQL は空気(実行時のオプション)が読めないようなので、設定ファイルではっきりと明示しておくしかなさそうだ。

なるほど。明示的にしておこう。

[root@localhost etc]# emacs /etc/my.cnf
↑で
default-character-set=utf8
skip-character-set-client-handshakedatadir=/var/lib/mysql
を追加した。


[mysqld]
default-character-set=utf8
skip-character-set-client-handshakedatadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1

[mysql.server]
user=mysql
basedir=/var/lib

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

これで、Mysqlとmongrelを再起動してみる。


Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'


うーむ、あかん・・・・おなじだ・・・・。

ふと思い立ち、
config/database.yml の文字コードを Shift_JIS から utf-8 にしてみる。
・・・アスキーコードしか使ってないし・・関係ないと思うけど・・・・。

Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'


うーん。見事に玉砕・・・。関係なかった・・・。


DBから作り直してみるか・・・。


mysql> drop database lr_portal_development;
Query OK, 14 rows affected (0.03 sec)

mysql> drop database lr_portal_test;
Query OK, 0 rows affected (0.00 sec)

mysql> drop database lr_portal_production;
Query OK, 1 row affected (0.00 sec)

↑DB削除。


ああー、今思うと、これって、文字化けとかの問題で、接続できないとかは、別問題か・・・。
まぁとりあえず、作ろう・・・。


mysql> create database lr_portal_development default character set utf8;
Query OK, 1 row affected (0.00 sec)
mysql> create database lr_portal_test default character set utf8;
Query OK, 1 row affected (0.00 sec)
mysql> create database lr_portal_production default character set utf8;
Query OK, 1 row affected (0.00 sec)


DB作成完了!

つぎに、migrate


[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SET NAMES 'utf8'

(See full trace by running task with --trace)


はぁ...。これっすよ...。

先ほどの、mysqlの設定で、rails側でutf8の宣言はいらなくなったはずなので、
おもむろに、
config/database.yml の
encoding: utf8
を削除して rake migrate してみる。

[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


あ!!!反応変わった!!!
config/database.yml の記法ミス??だったのか??

しかも、このエラーは昨日見たような・・・。


mysql> use lr_portal_development
Database changed
mysql> CREATE TABLE schema_info
-> (
-> version INT NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)

mysql>


昨日と同じようにう作ってみる。


mysql> insert into schema_info set version=0;
Query OK, 1 row affected (0.01 sec)


これで、 rake db:migrate


[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)


あれーーー??

あ、権限設定してない・・・。

mysql> grant all privileges on lr_portal_production.* to rails@localhost identified by 'rails_rails' with grant option;
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on lr_portal_development.* to rails@localhost identified by 'rails_rails' with grant option
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on lr_portal_test.* to rails@localhost identified by 'rails_rails' with grant option;
Query OK, 0 rows affected (0.00 sec)


これで、やってみる。

[root@localhost lr_portal]# rake db:migrate
(in /srv/www/lighttpd/lr_portal)
rake aborted!
Mysql::Error: Lost connection to MySQL server during query: SELECT version FROM schema_info

(See full trace by running task with --trace)

ぐはーーー。
なんなんだろう・・・・。


http://d.hatena.ne.jp/niraikanaibird/searchdiary?word=*[mysql]
http://rails.office.drecom.jp/q1w2e3r4/daily/200606/30
↑これによると、

yum install mysql-devel
↑これして、
gem install mysql -- --with-mysql-config=`which mysql_config`
↑これするらしいが、
yum install mysql-devel
↑これが失敗する。

[root@localhost /]# yum install mysql-devel
Loading "installonlyn" plugin
Loading "fastestmirror" plugin
Loading "priorities" plugin
Setting up Install Process
Setting up repositories
Loading mirror speeds from cached hostfile
Reading repository metadata in from local files
0 packages excluded due to repository priority protections
Parsing package install arguments
Nothing to do

これを成功させよう・・・。

その前に・・・。
インストールされているパッケージを確認。

http://www.linux.or.jp/JF/contrib/LILO-doc/rpm-3.html
[root@localhost /]# rpm -qa | grep mysql
mysql-5.0.22-2.1
mysql-bench-5.0.22-2.1
libdbi-dbd-mysql-0.8.1a-1.2.2
mod_auth_mysql-3.0.0-3.1
mysql-connector-odbc-3.51.12-2.2
mysql-devel-5.0.22-2.1
mysql-server-5.0.22-2.1
php-mysql-5.1.6-11.el5


入ってるし!!!
mysql-devel-5.0.22-2.1

ぢゃあ、
gem install mysql -- --with-mysql-config=`which mysql_config`
こっちの問題か・・・。


http://d.hatena.ne.jp/catalina/searchdiary?word=*[shopping%20cart]
↑このページには、
gem install mysql -- --with-mysql-config=/usr/bin/mysql_config
と書いてあるので、やってみる。


[root@localhost /]# gem install mysql -- --with-mysql-config=/usr/bin/mysql_config
Attempting local installation of 'mysql'
Local gem file not found: mysql*.gem
Attempting remote installation of 'mysql'
Select which gem to install for your platform (i386-linux)
1. mysql 2.7.3 (mswin32)
2. mysql 2.7.1 (mswin32)
3. mysql 2.7 (ruby)
4. mysql 2.6 (ruby)
5. mysql 2.5.1 (ruby)
6. Cancel installation
> 3
Building native extensions. This could take a while...
mysql.c: In function ‘make_field_obj’:
mysql.c:185: 警告: unused variable ‘hash’
mysql.c: In function ‘stmt_execute’:
mysql.c:1316: 警告: unused variable ‘false’
mysql.c: In function ‘time_initialize’:
mysql.c:1703: 警告: control reaches end of non-void function
mysql.c: In function ‘stmt_execute’:
mysql.c:1365: 警告: ‘t.time_type’ is used uninitialized in this function
mysql.c:1378: 警告: ‘t.time_type’ is used uninitialized in this function
ruby extconf.rb install mysql -- --with-mysql-config=/usr/bin/mysql_config
checking for mysql_ssl_set()... yes
checking for mysql.h... yes
creating Makefile

make
gcc -I. -I. -I/usr/lib/ruby/1.8/i386-linux -I. -DHAVE_MYSQL_SSL_SET -DHAVE_MYSQL_H -I/usr/include/mysql -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv -fPIC -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -Wall -fPIC -c mysql.c
gcc -shared -L"/usr/lib" -o mysql.so mysql.o -lruby -L/usr/lib/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib -lssl -lcrypto -lpthread -ldl -lcrypt -lm -lc

make install
/usr/bin/install -c -m 0755 mysql.so /usr/lib/ruby/gems/1.8/gems/mysql-2.7/lib
Successfully installed mysql-2.7
[root@localhost /]#


これって成功なの???


もちつけ、もちつくんだ。

昨日は、rootパスワード設定前で、ちゃんとアクセスできたんだ。
rootのパスワードを設定した瞬間から、はじかれるようになった。
ということで、パスワードをセットする前にしてみよう。

mysql> use mysql
mysql> SET PASSWORD FOR root@localhost=PASSWORD('');


これで、root のパスワードをなしにする。
そして、rake migrate

[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
== CreateUnits: migrating =====================================================
-- create_table(:units)
-> 0.0081s
== CreateUnits: migrated (0.0087s) ============================================

== CreatePositions: migrating =================================================
-- create_table(:positions)
-> 0.0044s
== CreatePositions: migrated (0.0050s) ========================================

== CreateWorkForms: migrating =================================================
-- create_table(:work_forms)
-> 0.0162s
== CreateWorkForms: migrated (0.0167s) ========================================

== CreateUserAuthorizations: migrating ========================================
-- create_table(:user_authorizations)
-> 0.0043s
== CreateUserAuthorizations: migrated (0.0049s) ===============================

== CreateCompanyDirectories: migrating ========================================
-- create_table(:company_directories)
-> 0.0085s
== CreateCompanyDirectories: migrated (0.0091s) ===============================

== CreateUsers: migrating =====================================================
-- create_table(:Users)
-> 0.0047s
== CreateUsers: migrated (0.0053s) ============================================

== CreateChangeLogs: migrating ================================================
-- create_table(:change_logs)
-> 0.0065s
== CreateChangeLogs: migrated (0.0071s) =======================================

== CreateAuthentications: migrating ===========================================
-- create_table(:authentications)
-> 0.0047s
== CreateAuthentications: migrated (0.0054s) ==================================

== CreateAuthResponses: migrating =============================================
-- create_table(:auth_responses)
-> 0.0051s
== CreateAuthResponses: migrated (0.0057s) ====================================

== CreateReports: migrating ===================================================
-- create_table(:reports)
-> 0.0052s
== CreateReports: migrated (0.0059s) ==========================================

== CreateComments: migrating ==================================================
-- create_table(:comments)
-> 0.0053s
== CreateComments: migrated (0.0058s) =========================================

== CreateReportTypes: migrating ===============================================
-- create_table(:report_types)
-> 0.0043s
== CreateReportTypes: migrated (0.0049s) ======================================

== CreateReportsAuthentications: migrating ====================================
-- create_table(:reports_authentications)
-> 0.0046s
== CreateReportsAuthentications: migrated (0.0052s) ===========================


おおおおぉぉぉ。うまくいく・・・。
なんでパスワード設定するとだめなの・・・?

とりあえず、root のままでは、マズいので、他のユーザーを設定する。

ユーザーを rails にしてやってみよう。

とりあえず、
[root@localhost lr_portal]# rake migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
== CreateReportsAuthentications: reverting ====================================
-- drop_table(:reports_authentications)
-> 0.0067s
== CreateReportsAuthentications: reverted (0.0072s) ===========================

== CreateReportTypes: reverting ===============================================
-- drop_table(:report_types)
-> 0.0027s
== CreateReportTypes: reverted (0.0033s) ======================================

== CreateComments: reverting ==================================================
-- drop_table(:comments)
-> 0.0024s
== CreateComments: reverted (0.0029s) =========================================

== CreateReports: reverting ===================================================
-- drop_table(:reports)
-> 0.0023s
== CreateReports: reverted (0.0030s) ==========================================

== CreateAuthResponses: reverting =============================================
-- drop_table(:auth_responses)
-> 0.0024s
== CreateAuthResponses: reverted (0.0030s) ====================================

== CreateAuthentications: reverting ===========================================
-- drop_table(:authentications)
-> 0.0027s
== CreateAuthentications: reverted (0.0032s) ==================================

== CreateChangeLogs: reverting ================================================
-- drop_table(:change_logs)
-> 0.0024s
== CreateChangeLogs: reverted (0.0029s) =======================================

== CreateUsers: reverting =====================================================
-- drop_table(:users)
rake aborted!
Mysql::Error: #42S02Unknown table 'users': DROP TABLE users

(See full trace by running task with --trace)


で、DBを戻す。


それで、mysql のユーザー作成。


mysql> grant all privileges on lr_portal_development.* to rails@localhost identified by '' with grant option;

で、パスワードなしで作ってみる。

config/database.yml の接続 username を rails にしてやってみる。


[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
== CreateChangeLogs: migrating ================================================
-- create_table(:change_logs)
-> 0.0102s
== CreateChangeLogs: migrated (0.0108s) =======================================

== CreateAuthentications: migrating ===========================================
-- create_table(:authentications)
-> 0.0052s
== CreateAuthentications: migrated (0.0058s) ==================================

== CreateAuthResponses: migrating =============================================
-- create_table(:auth_responses)
-> 0.0049s
== CreateAuthResponses: migrated (0.0054s) ====================================

== CreateReports: migrating ===================================================
-- create_table(:reports)
-> 0.0055s
== CreateReports: migrated (0.0061s) ==========================================

== CreateComments: migrating ==================================================
-- create_table(:comments)
-> 0.0176s
== CreateComments: migrated (0.0182s) =========================================

== CreateReportTypes: migrating ===============================================
-- create_table(:report_types)
-> 0.0222s
== CreateReportTypes: migrated (0.0227s) ======================================

== CreateReportsAuthentications: migrating ====================================
-- create_table(:reports_authentications)
-> 0.0043s
== CreateReportsAuthentications: migrated (0.0049s) ===========================

[root@localhost lr_portal]#


おおおおおおぉ。ユーザー名 rails でいけた!!!
なんでパスワード設定するとだめなの????

ということで、root はパスワード設定する。

mysql> SET PASSWORD FOR root@localhost=PASSWORD('******');
Query OK, 0 rows affected (0.00 sec)

これで、rake migrate ができなくなったってことないよな・・・。

[root@localhost lr_portal]# rake migrate VERSION=0
(in /srv/www/lighttpd/lr_portal)
== CreateReportsAuthentications: reverting ====================================
-- drop_table(:reports_authentications)
-> 0.0080s
== CreateReportsAuthentications: reverted (0.0085s) ===========================

== CreateReportTypes: reverting ===============================================
-- drop_table(:report_types)
-> 0.0028s
== CreateReportTypes: reverted (0.0034s) ======================================

== CreateComments: reverting ==================================================
-- drop_table(:comments)
-> 0.0024s
== CreateComments: reverted (0.0029s) =========================================

== CreateReports: reverting ===================================================
-- drop_table(:reports)
-> 0.0027s
== CreateReports: reverted (0.0033s) ==========================================

== CreateAuthResponses: reverting =============================================
-- drop_table(:auth_responses)
-> 0.0027s
== CreateAuthResponses: reverted (0.0033s) ====================================

== CreateAuthentications: reverting ===========================================
-- drop_table(:authentications)
-> 0.0026s
== CreateAuthentications: reverted (0.0032s) ==================================

== CreateChangeLogs: reverting ================================================
-- drop_table(:change_logs)
-> 0.0025s
== CreateChangeLogs: reverted (0.0030s) =======================================

== CreateUsers: reverting =====================================================
-- drop_table(:users)
rake aborted!
Mysql::Error: #42S02Unknown table 'users': DROP TABLE users

(See full trace by running task with --trace)
[root@localhost lr_portal]# rake migrate
(in /srv/www/lighttpd/lr_portal)
== CreateChangeLogs: migrating ================================================
-- create_table(:change_logs)
-> 0.0107s
== CreateChangeLogs: migrated (0.0112s) =======================================

== CreateAuthentications: migrating ===========================================
-- create_table(:authentications)
-> 0.0054s
== CreateAuthentications: migrated (0.0060s) ==================================

== CreateAuthResponses: migrating =============================================
-- create_table(:auth_responses)
-> 0.0052s
== CreateAuthResponses: migrated (0.0057s) ====================================

== CreateReports: migrating ===================================================
-- create_table(:reports)
-> 0.0054s
== CreateReports: migrated (0.0060s) ==========================================

== CreateComments: migrating ==================================================
-- create_table(:comments)
-> 0.0058s
== CreateComments: migrated (0.0064s) =========================================

== CreateReportTypes: migrating ===============================================
-- create_table(:report_types)
-> 0.0043s
== CreateReportTypes: migrated (0.0049s) ======================================

== CreateReportsAuthentications: migrating ====================================
-- create_table(:reports_authentications)
-> 0.0047s
== CreateReportsAuthentications: migrated (0.0053s) ===========================

[root@localhost lr_portal]#


む大丈夫だ!!
うごく!!

とりあえず、これでよい。
パスワード設定は、違うタスクでやろう・・・。


19.development で動いている、production で動かさないとな。
――――――――――――――――――――――――――――――――――――――――
はぁ・・・長かった・・・。
とりあえず、ユーザー名 rails パスワードなし。で動かすとして、
(パスワード設定は違うタスクでやる。)


で、次!!


今は、DBが development で動いている。

それを、production で動かそうと言うことをやる。

「mongrel production」でググって見る。

http://d.hatena.ne.jp/pushiganga/20070422
↑には
>rake db:migrate RAILS_ENV=production
と書いてある。migrateでは、↑やるのか?

mongrel はどうやるんだ??
なんか、前見たな・・・・。

http://www.fkino.net/hiki/?MongrelInstall
↑には、
mongrel_rails start -p 10080 -d -e production

と書いてある。
やってみよう。

[root@localhost lr_portal]# rake db:migrate RAILS_ENV=production
(in /srv/www/lighttpd/lr_portal)
rake aborted!
#28000Access denied for user 'rails'@'localhost' (using password: YES)

(See full trace by running task with --trace)


ぐはー。


あああ、権限設定か・・・。

mysql> grant all privileges on lr_portal_test.* to rails@localhost identified by '' with grant option;
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on lr_portal_production.* to rails@localhost identified by '' with grant option;
Query OK, 0 rows affected (0.00 sec)


これでやってみよう。


[root@localhost lr_portal]# rake db:migrate RAILS_ENV=production
(in /srv/www/lighttpd/lr_portal)
rake aborted!
#28000Access denied for user 'rails'@'localhost' (using password: YES)

(See full trace by running task with --trace)
[root@localhost lr_portal]#


ぐはーーーー。なんで?
あ!!

config/database.yml の更新忘れてた・・・。

更新、アップ、それで再度やってみる。

[root@localhost lr_portal]# rake db:migrate RAILS_ENV=production
(in /srv/www/lighttpd/lr_portal)
== CreateUnits: migrating =====================================================
-- create_table(:units)
-> 0.0057s
== CreateUnits: migrated (0.0063s) ============================================

== CreatePositions: migrating =================================================
-- create_table(:positions)
-> 0.0043s
== CreatePositions: migrated (0.0049s) ========================================

== CreateWorkForms: migrating =================================================
-- create_table(:work_forms)
-> 0.0041s
== CreateWorkForms: migrated (0.0047s) ========================================

== CreateUserAuthorizations: migrating ========================================
-- create_table(:user_authorizations)
-> 0.0282s
== CreateUserAuthorizations: migrated (0.0288s) ===============================

== CreateCompanyDirectories: migrating ========================================
-- create_table(:company_directories)
-> 0.0118s
== CreateCompanyDirectories: migrated (0.0124s) ===============================

== CreateUsers: migrating =====================================================
-- create_table(:Users)
-> 0.0048s
== CreateUsers: migrated (0.0053s) ============================================

== CreateChangeLogs: migrating ================================================
-- create_table(:change_logs)
-> 0.0050s
== CreateChangeLogs: migrated (0.0055s) =======================================

== CreateAuthentications: migrating ===========================================
-- create_table(:authentications)
-> 0.0049s
== CreateAuthentications: migrated (0.0056s) ==================================

== CreateAuthResponses: migrating =============================================
-- create_table(:auth_responses)
-> 0.0050s
== CreateAuthResponses: migrated (0.0055s) ====================================

== CreateReports: migrating ===================================================
-- create_table(:reports)
-> 0.0229s
== CreateReports: migrated (0.0234s) ==========================================

== CreateComments: migrating ==================================================
-- create_table(:comments)
-> 0.0049s
== CreateComments: migrated (0.0055s) =========================================

== CreateReportTypes: migrating ===============================================
-- create_table(:report_types)
-> 0.0070s
== CreateReportTypes: migrated (0.0075s) ======================================

== CreateReportsAuthentications: migrating ====================================
-- create_table(:reports_authentications)
-> 0.0042s
== CreateReportsAuthentications: migrated (0.0047s) ===========================

[root@localhost lr_portal]#


おおおおぉ。成功!!!
ちゃんと確認してみる。


mysql> use lr_portal_production
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+--------------------------------+
| Tables_in_lr_portal_production |
+--------------------------------+
| Users |
| auth_responses |
| authentications |
| change_logs |
| comments |
| company_directories |
| positions |
| report_types |
| reports |
| reports_authentications |
| schema_info |
| units |
| user_authorizations |
| work_forms |
+--------------------------------+
14 rows in set (0.00 sec)


うむ。ちゃんとできてる。

あとは、mongrel!!

さっきの調べで、

mongrel_rails start -p 10080 -d -e production

とやると production のDB を見ると書いてあった。
というか、ポートは 3000 でよいので、

mongrel_rails start -p 3000 -d -e production

となるのか?

とりあえず、やってみる。

[root@localhost lr_portal]# mongrel_rails start -p 3000 -d -e production
[root@localhost lr_portal]#

なんか、シンプルな反応だな・・・。オプションの影響か...。

でアクセスしてみる。

http://10.20.138.111:3000/

おお見れる!!!

色々更新してみる。
おおおおおおぉ、色々更新可能!!!DBと連携している!!

では、mysql の lr_portal_production の中身を見てみましょう。


mysql> use lr_portal_production
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+--------------------------------+
| Tables_in_lr_portal_production |
+--------------------------------+
| Users |
| auth_responses |
| authentications |
| change_logs |
| comments |
| company_directories |
| positions |
| report_types |
| reports |
| reports_authentications |
| schema_info |
| units |
| user_authorizations |
| work_forms |
+--------------------------------+
14 rows in set (0.00 sec)

mysql> select * from positions;
+----+-----------------------+
| id | position_name |
+----+-----------------------+
| 1 | 代表取締役社長 |
+----+-----------------------+
1 row in set (0.00 sec)

mysql>


おおおおおおおぉお。
lr_portal_production が更新されてる!!!

だいじょうぶだ!!

とりあえず、これで完了。


20.課題点
――――――――――――――――――――――――――――――――――――――――
1.railsに設定するユーザーにパスワードを付けると、アクセスできなくなるので、
 パスワードつきでアクセスできるようにする。あとでやろう。

mongrel を port 3000 ではなく、port 80 で動かす。

1.mongrel を port 3000 ではなく、port 80 で動かす。
――――――――――――――――――――――――――――――――――――――――

まず、port 80 は apache が占領しているので、排除する。

chkconfig httpd off

[root@localhost conf.d]# chkconfig httpd off
[root@localhost conf.d]#


つぎに、mongrel を 80 で起動する。

mongrel_rails start -p 80 -d -e production

[root@localhost conf.d]# cd /srv/www/lighttpd/lr_portal/
[root@localhost lr_portal]# mongrel_rails start -p 80 -d -e production
** !!! PID file log/mongrel.pid already exists. Mongrel could be running already. Check your log/mongrel.log for errors.
** !!! Exiting with error. You must stop mongrel and clear the .pid before I'll attempt a start.
[root@localhost lr_portal]#


ぬおおお、エラーー!
>Mongrel could be running already.

すでに、走ってるらしい。

では、まず、停止。

[root@localhost lr_portal]# mongrel_rails stop
Sending TERM to Mongrel at PID 9877...Done.
[root@localhost lr_portal]#

うむ停止。

[root@localhost lr_portal]# mongrel_rails start -p 80 -d -e production
[root@localhost lr_portal]#

お!動いた??

アクセスしてみる。

http://10.20.138.111/


あれ??エラーだ!!

正常に接続できませんでした


10.20.138.111 のサーバへの接続を確立できませんでした。


なんで??


port 80に何か・・・。
ファイヤーウォール??


あ、lighttpd・・・そういえば、
前、ポート80にした記憶がアル・・・。

[root@localhost lr_portal]# /etc/init.d/lighttpd stop
lighttpd を停止中: [ OK ]

さらに!

[root@localhost lr_portal]# chkconfig lighttpd off
[root@localhost lr_portal]#

これで、

[root@localhost lr_portal]# mongrel_rails start -p 80 -d -e production
[root@localhost lr_portal]#

アクセスしてみる。

http://10.20.138.111/

キタ━━━━(゚∀゚)━━━━ッ!!?

これで、ポート 80 で見れた!!

2007年05月09日

config/routes.rb のURL書き換え機能 (Ruby on Rails)

>Rubyで書かれたRails用の mod_rewrite のようなURL書き換え機能です。定義ファイルは config/routes.rb です。

config/routes.rb の例:
ActionController::Routing::Routes.draw do |map|
  map.connect '', :controller => "berryz", :action=> "index"  # DirectoryIndex の例
  map.connect ':controller/:action/:id'                       # Rails のデフォルトの書き換え例
end

上記設定の接続例:
   1. http://localhost:3000/ にアクセス (パスは"")
   2. route の1つめの定義の ^$ にマッチ
   3. route の1つめの指示で "berryz"コントローラの"index"アクションを呼び出す
   4. BerryzController#index を実行
   5. そこで render された内容をページとして表示

○参考
http://wota.jp/ac/?date=20050725

2007年05月23日

Ruby on Rails テスト

memo

http://www.ark-web.jp/sandbox/wiki/index.php?%CA%D9%B6%AF%B2%F1%2FRails%A4%CB%A4%E8%A4%EB%A5%C6%A5%B9%A5%C8%BA%EE%C0%AE
http://jp.rubyist.net/magazine/?cmd=view&p=0013-RubyOnRails&key=test
http://www.ruby-lang.org/ja/man/?cmd=view;name=Test%3A%3AUnit
http://pub.cozmixng.org/~hiki/programming/?(Test%3A%3AUnit)%A5%C1%A5%E5%A1%BC%A5%C8%A5%EA%A5%A2%A5%EB
http://manuals.rubyonrails.com/read/book/5
http://api.rubyonrails.org/classes/Test/Unit/Assertions.html

2007年05月29日

Ruby on Rails 「XSS」対策

Railsでは、ビュー(rhtml)内で h と言うメソッドを利用することで、簡単にHTMLサニタイジングを行うことが出来ます。

<%= params[:name] %>

↓ ↓ ↓

<%=h params[:name] %>

Ruby on Rails 「SQLインジェクション : SQL Injection」対策

RailsではActiveRecordがクエリのプレースフォルダ機能を提供しています。プレースフォルダとは、SQLコマンドと実際の値を分離する方法で、SQL中には「この部分に変数が入ります」と言う宣言をしておいて、クエリ実行時に変数を渡して内部的に完全なクエリを作成します。

ActiveRecordには、DBIで使われている'?'パラメータ記法と、名前付きパラメータ記法の2種類のプレースフォルダがあります。

'?'パラメータ
Food.find(:all, :conditions=>["name = ?", params[:name]])

名前付きパラメータ
Food.find(:all, :conditions=>["name = :name", :name=>params[:name]])

どちらの場合も、ActiveRecordが内部的に、引数をサジタイニングして取得クエリを作成&実行してくれます。

2007年06月07日

Rails :includeオプション

>ARにはincludeオプションと言う素晴らしい機能が用意されています。"AR.find"に :include=>(関連名) というオプションを渡すだけで、自動的にJOINクエリを内部で作成し、さらに結果オブジェクトに対してそれぞれの関連先のオブジェクトまで準備してくれるのです。

:include オプション・・・す・・・すばらしい。

2007年06月11日

リダイレクトするとアンカーが削除される

http://d.hatena.ne.jp/mihael2/20060712/1152682613

IEで redirect_to と anchor を組み合わせて使うと、アンカーが削除されるどころか、エラーになって表示されない。解決しよう。

2007年06月14日

RailsとSSL

はてなはただ - RailsとSSL

memoです。SSLやらないといけないので...。

ヽ( ・∀・)ノくまくまー(2007-06-05)
Rails で行こう! - Ruby on Rails を学ぶ - SSL 上で WEBrick を動かす
capsctrldays(2006-05-10)

2007年06月19日

Railsでモックを実現

http://www.thinkit.co.jp/cert/article/0608/12/4/3.htm

memoです。

 ソースはリスト8~10のようになります。

リスト8:Railsでのモッククラス(/test/mocks/test/credit_card_auth.rb)
require 'models/credit_card_auth'
class CreditCardAuth
   def auth(card_no)
      return true
   end
end

リスト9:Railsでの本番クラス(/app/models/credit_card_auth.rb)
class CreditCardAuth < ActiveRecord::Base
   def auth(card_no)
      #クレジットカード処理を記述
      ...
   end
end

リスト10:Railsでの呼び出し側クラス
class ItemController < ApplicationController
   def buy
      card_auth = CreditCardAuth.new
      card_result = card_auth.auth(params[:card_no])
      (中略)
   end
   (中略)
end


この機構は、Rubyの「Open Class」などと呼ばれる特徴を利用しています。Open Classとは「再オープン可能なクラス」という意味で、何回でもクラスを再宣言してメソッドを追加したり上書いたりできる機構です。

カレンダー


2007年06月
Su Mo Tu We Th Fr Sa
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Map

About rails

ブログ「プログラマ 福重 伸太朗 ~基本へ帰ろう~」のカテゴリ「rails」に投稿されたすべてのエントリーのアーカイブのページです。過去のものから新しいものへ順番に並んでいます。

次のカテゴリは本日のメソッドです。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。