2010年7月29日木曜日

rails duplicate habtm 二重に多対多備忘録

 Hoges と Fugas が多対多の関係で欲しい場合は、habtm を使えばシンプルに済みます。しかし、この多対多の関係が、もうひとつ欲しい・・・となったとき、?????かなり悩んだ

create table hoges (
id serial primary key,
name varchar(16)
);
create table fugas (
id serial primary key,
name varchar(16)
);
create table fugas_and_hoges (
id serial primary key,
fuga_id integer,
hoge_id integer
);
create table another_fugas_and_hoges (
id serial primary key,
fuga_id integer,
hoge_id integer
);

このようなテーブルに対して

class FugasAndHoge < ActiveRecord::Base
belongs_to :fuga
belongs_to :hoge
end

class AnotherFugasAndHoge < ActiveRecord::Base
belongs_to :fuga
belongs_to :hoge
end

class Fuga < ActiveRecord::Base
has_many :fugas_and_hoges, :dependent => :destroy
has_many :hoges, :through => :fugas_and_hoges, :dependent => :destroy
has_many :another_fugas_and_hoges, :dependent => :destroy
has_many :another_hoges, :source => :hoge, :through => :another_fugas_and_hoges, :dependent => :destroy
end


class Hoge < ActiveRecord::Base
has_many :fugas_and_hoges, :dependent => :destroy
has_many :fugas, :through => :fugas_and_hoges, :dependent => :destroy
has_many :another_fugas_and_hoges, :dependent => :destroy
has_many :another_fugas, :source => :fuga, :through => :another_fugas_and_hoges, :dependent => :destroy
end



 うーむ・・・

0 件のコメント: