Rails 2.0・その22(fixture の ID は基本不要)
fixture で、id の値を省くと、ラベルのハッシュ値が id として使用されます。
activerecord-2.0.2/lib/active_record/fixtures.rb にそう書いてありました。
def self.identify(label)
label.to_s.hash.abs
end
なので yaml 形式の fixture は、例えば以下のように書くことができます。
people テーブルに、name と age カラムがある場合
Rails2.0
test/fixtures/people.yml
dave:
name: Dave Smith
age: 11
mike:
name: Mike Howdy
age: 32
↑id:1などと、自分で id を振っても別に構わないです。面倒臭いけど。
Rails1.2
dave:
id:1
name: Dave Smith
age: 11
mike:
id:2
name: Mike Howdy
age: 32
あと、belongs_to 関係にあるときは、属している親のラベル名を指定することができますよ。
Rails2.0
test/fixtures/people.yml
dave:
name: Dave Smith
age: 11
country: us
mike:
name: Mike Howdy
age: 32
country: uk
test/fixtures/countries.yml
us:
name: The United States
capital: Washington D.C.
uk:
name: The United Kingdom
capital: London
キュッ キュキュッ キュキュッ キュキュキュ ダーテニヤスクハアリマセリーヌディオーン
【広告】