2011-01-24

ActiveRecordで多対多の関係に属性を持たせる

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
ActiveRecordで多対多の関係を表現するには
has_and_belongs_to_many
を使うもんだと思い込んでいました。

ある人がある商品を買った場合では以下のような感じです。
class User < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :users
end
商品を一つづつしか買えないのならいいですが、たいてい複数個買えたりすると思います。 多対多の関係に何個買ったかという属性をつけたいと思ったわけです。 そんな時は、 has_many :through を使えばよかったことに今更に気づいてみました。 人と商品の関係を注文として定義することにします。
class User < ActiveRecord::Base
  has_many :orders
  has_many :items, :through => :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
end

class Item < ActiveRecord::Base
  has_many :orders
  has_many :users, :through => :orders
end
これでOrderモデルに何個買ったかを定義させることができるというわけです。 このとき、うっかり has_many :orders を書き忘れて
class User < ActiveRecord::Base
  has_many :items, :through => :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
end

class Item < ActiveRecord::Base
  has_many :users, :through => :orders
end
と書いてしまうと ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association という感じのエラーが出たりします。 以下のサイトを参考にさせていただきました。 http://wiki.usagee.co.jp/ruby/rails/RailsGuides%E3%82%92%E3%82%86%E3%81%A3%E3%81%8F%E3%82%8A%E5%92%8C%E8%A8%B3%E3%81%97%E3%81%A6%E3%81%BF%E3%81%9F%E3%82%88/Active%20Record%20Associations#v41bb3f5

0 件のコメント: