has_manyのJoinモデル

Rails Recipesの#22から、関連自体にデータを持たせたいときなどに使うJoinモデル。そのオプションに関してもメモ。belongs_toやhas_manyで使えるオプションにclass_nameがあるが、これがJoinモデルを使った時はclass_nameではなくsourceになる。

class_nameの場合:
class User < ActiveRecord::Base
  has_many :videos
  has_many :shinchaku_videos,
           :class_name => "Video",
           :conditions => "shinchaku is not null"
end
Joinモデルの場合:
class Employee < ActiveRecord::Base
  has_many :shozokus
  has_many :departments, :through => :shozokus
  has_many :previous_shozokus,
           :through => :shozokus,
           :source => :department,
           :conditions => ['end_date is not null' ]
end