9

我有一个表Foo,它具有bar多态性belongs_to关联。 foos表具有标准bar_id列。但是,而不是基于字符串的bar_type列,我有一个整数bar_type_id列。本栏参考表bar_types中的id列。 bar_types.name保存表示特定bar实例的类的类的名称。使用整数ID类型字段的多态关联

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

+2

至于它是不是非标准态关联你应该把它写自己。 – fl00r 2011-05-25 21:45:29

回答

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 
0

有两种方法。

首先很简单:

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

其次可能是棘手:

set_inheritance_column :bar_type_id 
0

我不知道,但你可以玩

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

我正在使用polymorphic integer type宝石,写由我的同事之一。在我看来,它比上面给出的例子稍微简单一些。例如,在配置映射后,您更改:

belongs_to :actor,    polymorphic: true 

为新的格式:

belongs_to :actor,    polymorphic: true, integer_type: true