n:n のリレーションシップ

解決. 中間テーブルを使って, has_and_belongs_to_many().

例えば papers と authors のリレーションを作成したい, とする.

  • paper には複数の author がいる(場合もある).
  • author は沢山 paper を書いている(…場合もある).

この場合, migration は

def self.up
  creata_table(:authors_papers, :id=>false) do |table|
    table.column(:author_id, :integer)
    table.column(:paper_id, :integer)
  end
end

def self.down
  drop_table(:authors_papers)
end

みたいにして. primary_key は author_id と paper_id から一意に決まるので不要. あると id を上書きして祟るので, false にしておく.

あとは

# app/models/paper.rb
class Paper < ActiveRecord::Base
  has_and_belongs_to_many(:authors)
end

# app/models/author.rb
class Author < ActiveRecord::Base
  has_and_belongs_to_many(:papers)
end

でリレーションが完成.
paper.authors や author.papers では配列が返されるようになる.

あとは view の設定だけかな. 楽だわー Rails.