使用整数ID类型字段的多态关联

我有一个表Foo ,它有一个名为bar的多态belongs_to关联。 foos表具有标准bar_id列。 但是,我有一个整数bar_type_id列,而不是基于字符串的bar_type_id列。 此列引用表bar_typesid列。 bar_types.name保存表示特定bar实例的类的类的名称。

Rails(理想情况下> = 2.3.10)是否允许这种类型的多态关联?

我们通过覆盖新模块中的association_class方法并使用:extend选项包含它来完成它。 还创建了一个整数到字符串映射哈希,以使事情更容易。

config/initializers目录或您喜欢的任何地方,创建一个文件并定义散列INT_OBJECT_TYPE_TO_CLASSNAME = { 0 => "Project", 1 => "Task", 2 => "Timesheet" }

 class CommentObjectType < ActiveRecord::Base module ClassNamesAsInt def association_class return INT_OBJECT_TYPE_TO_CLASSNAME[restricted_object_type].constantize end end end 

在comments.rb中

 belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt 

我正在使用我的一个同事写的多态整数类型 gem。 在我看来,它比上面给出的例子稍微容易一些。 例如,在配置映射后,您将从以下位置更改:

 belongs_to :actor, polymorphic: true 

新格式:

 belongs_to :actor, polymorphic: true, integer_type: true 

这有两种方法。

首先很容易:

 has_many :bars, :conditions => "whatever you want" 

第二个可能很棘手:

 set_inheritance_column :bar_type_id 

我不确定,但你可以玩

 belongs_to :bar, :class_name => proc{ BarType.find(self.bar_type_id).name }, :foreign_key => :bar_id