Rails の fixtures の書き方を整理してみる

投稿者 okkez 2009-08-26 12:45:00 GMT

ほとんど以下に書いてあるけど、最近 fixtures の整理をしてるので書いてみる。

  • http://railsapi.com/doc/rails-v2.3.3.1/files/activerecord/lib/active_record/fixtures_rb.html

CSV とか single file とか色々あるけれどここでは YAML fixtures について書きます。

ラベルで参照する

pirates.yml
### in pirates.yml reginald: id: 1 name: Reginald the Pirate monkey_id: 1 ### in monkeys.yml george: id: 1 name: George the Monkey pirate_id: 1

上記のようなものが以下のように書けます。

  ### in pirates.yml

  reginald:
    name: Reginald the Pirate
    monkey: george

  ### in monkeys.yml

  george:
    name: George the Monkey
    pirate: reginald

polymorphic belongs_to

今日一番の収穫がこれ。

  ### in fruit.rb
  class Fruit < ActiveRecord::Base
    belongs_to :eater, :polymorphic => true
  end

  ### in fruits.yml

  apple:
    id: 1
    name: apple
    eater_id: 1
    eater_type: Monkey

こんな風に書いていたのが、こう書けます。

  ### in fruits.yml
  apple:
    eater: george (Monkey)

今、修正している Rails アプリではポリモーフィック関連をたくさん使っているのでこれはすごく便利です。

belongs_to 応用

こんなモデル定義がある場合にはちょっと変わった書き方ができます。

# in expense.rb
class Expense < ActiveRecord::Base
  has_many :expense_details
end
# in expense_detail.rb
class ExpenseDetail < ActiveRecord::Base
  belongs_to :header, :class_name => 'Expense', :foreign_key => 'expense_id'
end

普通は belongs_to :expense と書きますが、上のように書くことで header と書けるようになります。

### expenses.yml
hawaii:
  title: hawaii trip!

### expense_details.yml
chocorate:
  name: chocorate
  header: hawaii

nested set を使っているとき

nested set を使っている時はこう書けます。

### menus.yml
root:
  name: root
  parent_id:
menu_1:
  name: menu_1
  parent_id: <%= Fixtures.identify(:root) %>

$LABEL

$LABEL を使うと上の menus.yml がこうなります。

### menus.yml
root:
  name: $LABEL
  parent_id:
menu_1:
  name: $LABEL
  parent_id: <%= Fixtures.identify(:root) %>

他にもまだまだ便利な書き方はたくさんありそうです。

カテゴリ ,  | タグ  | コメントなし | トラックバックなし

コメント

トラックバック

トラックバックリンク:
http://typo.okkez.net/trackbacks?article_id=260

コメントは許可されていません