我使用的是传统的数据库,所以我没有在数据模型的任何控制。他们使用了大量的多态链接/加入桌,这样

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。

我可以理解这样的数据模型可能带来的好处,但我主要是看一个大的缺点:使用约束无法保证数据的完整性。但很可惜,我不能再改变这一点。

但在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

这个作品,但我不知道是否将有更好的解决方案,使用多态关联。

有帮助吗?

解决方案

您可以覆盖列名,当然,但Rails的API的快速扫描并没有表现出我在任何地方,以覆盖多态“类型”一栏。所以,你就不能设置为“obj_name”。

这是丑陋的,但我认为你需要为表中每种类型的对象的HABTM。

您的可能能够做这样的事:

{:report => 'REPORT'}.each do |sym, text|
  has_and_belongs_to_many sym,
    :join_table => "person_links",
    :foreign_key => "obj_r_ident",
    :association_foreign_key => "per_ident",
    :conditions => "OBJ_NAME='#{text}'"
end

至少这样所有常见的东西,停留 DRY ,并可以方便地添加多个关系。

其他提示

至少像Rails 4.2.1的,可以传递foreign_type到belongs_to的声明指定的列的名称将被用于该多态关联“类型”

http://apidock.com/rails/v4.2.1/的ActiveRecord /协会/ ClassMethods / belongs_to的

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top