使用整数ID类型字段的多态关联 [英] Polymorphic Assocations using Integer ID type fields
问题描述
我有一个表Foo
,该表具有一个名为bar
的多态belong_to关联. foos
表具有标准的bar_id
列.但是,我有一个整数bar_type_id
列,而不是基于字符串的bar_type
列.此列引用表bar_types
中的id
列. bar_types.name
保存代表特定bar
实例的类的类的名称.
I have a table Foo
that has a polymorphic belongs_to association called bar
. The foos
table has the standard bar_id
column. However, instead of a string-based bar_type
column, I have an integer bar_type_id
column. This column references the id
column in the table bar_types
. bar_types.name
holds the name of the class that represents the class of the particular bar
instance.
Rails(理想情况下> = 2.3.10)是否允许这种类型的多态关联?
Does Rails (ideally >=2.3.10) allow for this type of polymorphic association?
推荐答案
我们通过在新模块中覆盖association_class
方法并使用:extend
选项将其包括在内来完成此操作.还创建了一个整数到字符串的映射哈希,以简化操作.
We did it by overriding the association_class
method in a new module and included it using the :extend
option. Also created a integer to string mapping hash to make things easier.
在config/initializers
目录或您喜欢的任何位置中,创建一个文件并定义哈希
INT_OBJECT_TYPE_TO_CLASSNAME = { 0 => "Project", 1 => "Task", 2 => "Timesheet" }
In config/initializers
directory or anywhere you like, create a file and define the hash
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
In comments.rb
belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt
这篇关于使用整数ID类型字段的多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!