我有一个表Foo
,它具有bar
多态性belongs_to关联。 foos
表具有标准bar_id
列。但是,而不是基于字符串的bar_type
列,我有一个整数bar_type_id
列。本栏参考表bar_types
中的id
列。 bar_types.name
保存表示特定bar
实例的类的类的名称。使用整数ID类型字段的多态关联
是否Rails(理想情况下> = 2.3.10)允许这种类型的多态关联?
我有一个表Foo
,它具有bar
多态性belongs_to关联。 foos
表具有标准bar_id
列。但是,而不是基于字符串的bar_type
列,我有一个整数bar_type_id
列。本栏参考表bar_types
中的id
列。 bar_types.name
保存表示特定bar
实例的类的类的名称。使用整数ID类型字段的多态关联
是否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
有两种方法。
首先很简单:
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
我正在使用polymorphic integer type宝石,写由我的同事之一。在我看来,它比上面给出的例子稍微简单一些。例如,在配置映射后,您更改:
belongs_to :actor, polymorphic: true
为新的格式:
belongs_to :actor, polymorphic: true, integer_type: true
至于它是不是非标准态关联你应该把它写自己。 – fl00r 2011-05-25 21:45:29