我正在使用遗留数据库,因此我无法控制数据模型.他们使用了很多多态链接/连接表,就像这样
create table person(per_ident, name, ...)
create table person_links(per_ident, obj_name, obj_r_ident)
create table report(rep_ident, name, ...)
Run Code Online (Sandbox Code Playgroud)
obj_nametable-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)
Run Code Online (Sandbox Code Playgroud)
然后,人1将有2个链接报告,1和2.
我可以理解像这样的数据模型可能带来的好处,但我主要看到一个很大的缺点:使用约束不可能确保数据完整性.但是,唉,我不能再改变它了.
但是要在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, …Run Code Online (Sandbox Code Playgroud)