私はレガシー データベースを使用しているため、データモデルを制御できません。このように、多くの多態的なリンク/結合テーブルを使用します
create table person(per_ident, name, ...)
create table person_links(per_ident, obj_name, obj_r_ident)
create table report(rep_ident, name, ...)
はobj_name
テーブル名、obj_r_ident
は識別子です。したがって、リンクされたレポートは次のように挿入されます。
insert into person(1, ...)
insert into report(1, ...)
insert into report(2, ...)
insert into person_links(1, 'REPORT', 1)
insert into person_links(1, 'REPORT', 2)
そして、人物 1 は 2 つのリンクされたレポート (1 と 2) を持つことになります。
このようなデータモデルを使用する利点は理解できますが、大きな欠点が 1 つあります。データの整合性を確保するために制約を使用することはできません。しかし、残念ながら、これを変更することはできません。
しかし、これをRailsで使用するために、ポリモーフィックな関連付けを調べていましたが、これを解決する良い方法が見つかりませんでした(列名を変更できず、それを行う方法がすぐに見つからなかったため)。
しかし、私は解決策を思いつきました。提案を提供してください。
class Person < ActiveRecord::Base
set_primary_key "per_ident"
set_table_name "person"
has_and_belongs_to_many :reports,
:join_table => "person_links",
:foreign_key => "per_ident",
:association_foreign_key => "obj_r_ident",
:conditions => "OBJ_NAME='REPORT'"
end
class Report < ActiveRecord::Base
set_primary_key "rep_ident"
set_table_name "report"
has_and_belongs_to_many :persons,
:join_table => "person_links",
:foreign_key => "obj_r_ident",
:association_foreign_key => "per_ident",
:conditions => "OBJ_NAME='REPORT'"
end
これは機能しますが、ポリモーフィックな関連付けを使用して、より良い解決策があるのではないかと思います。