fc2ブログ

2023.04 «  - 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 31 - - - » 2023.06
TOP > CATEGORY > [2.0]DB

TOP

Rails 2.0・その20(テーブル定義で belongs_to の関係を表すのも簡単に) 

2008年03月18日 ()
テーブルに依存関係がある場合、属しているテーブルの単数形_id というカラム名で、依存していますよー、ということを表せました。

2.0では、この「属しているテーブルの単数形_id」の代わりに、references や belongs_to を使って属していますということを表すことができます。

Rails 2.0

create_table :trains do |t|
  t.references :railway
  t.string :name, :null => false
  t.text :description
  t.float :max_speed, :null => false
  t.timestamps
end



上記の t.references を、t.belongs_to と書いても同じです。

もしくは、t.references :railway を、 t.integer :railway_id と書いてもやっぱり同じです。

Rails 1.2

create_table :trains do |t|
  t.column, "railway_id", :integer
  t.column, "name", :string, :null => false
  t.column, "description", :text
  t.column, "max_speed", :float, :null => false

  t.column, “created_at”, :datetime

  t.column, “updated_at”, :datetime
end



まあ、小さな違いですが、こういうこともできるということで。


【広告】

スポンサーサイト



[2008.03.18(Tue) 21:41] [2.0]DBTrackback(0) | Comments(0) 見る▼
↑TOPへ

Rails 2.0・その19(migrationカラム指定が簡単に) 

2008年03月11日 ()
migration ファイルが db/migrate ディレクトリの下に作成されたり、自分で作成したりします。

そのファイル中でのカラムの書き方がとても楽になりました。

例えば、books テーブルのカラムが title, first_name(20文字まで), last_name(20文字まで), price, created_at, updated_at だったとしたら、↓のように書くことができます。

[Rails2.0]

create_table :books do |t|
  t.string :title
  t.string :first_name, :last_name, :limit => 20
  t.integer :price
  t.timestamps
end



timestamps っていう一行で、created_at カラムと update_at カラムの2つのカラムが作成される、というのが注意点というか特筆点でしょうか。


以前は以下のような書き方でした。
[Rails1.2.3]

create_table :books do |t|
  t.column "title", :string
  t.column "first_name", :string, :limit => 20
  t.column "last_name", :string, :limit => 20
  t.column "price", :integer
  t.column "created_at", :datetime
  t.column "updated_at", :datetime
end




この t.[型名] の所に指定できる型名は以下のようです。

primary_key
string
text
integer
float
decimal
datetime
timestamp
time
date
binary
boolean



さらに t.[型名] の後にオプションもハッシュ型で追加できます。

:limit
→カラムの長さ
:default
→デフォルト値
:null
→null値を許すかどうか
:precision
→数字が全部で何桁か
:scale
→小数点以下何桁か



特に、precision や scale については DB 間の差が激しいので、公式マニュアルでもご覧になって、ご自分に合った返済プランをご計画ください。


【広告】

[2008.03.11(Tue) 00:17] [2.0]DBTrackback(0) | Comments(0) 見る▼
↑TOPへ

Rails 2.0・その18(デフォルトDBは sqlite3 そして商用DBはオプショナル) 

2008年03月06日 ()
rails コマンドを使って Ruby On Rails プロジェクトを作成すると、sqlite3 用のプロジェクトができあがります。

以下のようにすれば MySQL, PostgreSQL, Oracle などを指定することができます。

rails -d mysql プロジェクト名
rails -d postgresql プロジェクト名
rails -d oracle プロジェクト名
rails -d sqlite2 プロジェクト名
rails -d sqlite3 プロジェクト名



ちなみにSQLServerにつなぐには RORWiki を見た方がいいかも。

それから、商用DBのアダプタは Rails2.0 に同梱されていなくて、自分でインストールせねばならないようです。

gem install activerecord-oracle-adapter --source http://gems.rubyonrails.org
gem install activerecord-sqlserver-adapter --source http://gems.rubyonrails.org



【広告】

[2008.03.06(Thu) 23:57] [2.0]DBTrackback(0) | Comments(0) 見る▼
↑TOPへ

TOP