HABTMのFixtureはどこに書くの?

初めて HABTM (has_and_belongs_to_many) を使ってみました。テストデータを作ろうと思い 関連テーブル名.yml を作ったのですがエラーになってしまいました。

ネットで調べたのですが、なかなか見つからず Ryan's Scraps: What's New in Edge Rails: Fixtures Just Got a Whole Lot Easierでやっとわかりました。

結局 HABTM で関連しているテーブル用のfixture のどちらかに書けばよいのでした。しかもRailsのドキュメントにも書かれてました ^^); → http://api.rubyonrails.org/classes/Fixtures.html


それから関連テーブル名は関連する2つのテーブル名を並べますが、アルファベット順でないといけないのですね・・・

まとめ

Scheme

  create_table "employees", :force => true do |t|
    t.integer  "emp_no"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "employees_sections", :id => false, :force => true do |t|
    t.integer "employee_id", :null => false
    t.integer "section_id",  :null => false
  end

  create_table "sections", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Model

# employee.rb
class Employee < ActiveRecord::Base
  has_and_belongs_to_many :sections
end

# section.rb
class Section < ActiveRecord::Base
  has_and_belongs_to_many :employees
end

Fixture

# employees.yml
yamada:
  emp_no: 10001
  name: 山田太郎

kawada:
  emp_no: 10002
  name: 川田次郎

umida:
  emp_no: 10003
  name: 海田三郎


# sections.yml  
sales:
  name: 営業一課
  employees: yamada,kawada   # <-- employees_sections に書かれる

account:
  name: 経理課
  employees: umida           # <-- employees_sections に書かれる