【问题标题】:Polymorphic Assocations using Integer ID type fields使用整数 ID 类型字段的多态关联
【发布时间】:2011-05-25 21:40:56
【问题描述】:
我有一个表Foo,它有一个名为bar 的多态belongs_to 关联。 foos 表具有标准的 bar_id 列。但是,我有一个整数 bar_type_id 列,而不是基于字符串的 bar_type 列。此列引用表bar_types 中的id 列。 bar_types.name 包含代表特定 bar 实例的类的类的名称。
Rails(理想情况下 >=2.3.10)是否允许这种类型的多态关联?
【问题讨论】:
标签:
ruby-on-rails
polymorphic-associations
ruby-on-rails-2
【解决方案1】:
我们通过在新模块中覆盖 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
在 cmets.rb 中
belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt
【解决方案2】:
我正在使用由我的一位同事编写的 polymorphic integer type gem。在我看来,它比上面给出的例子更容易使用。例如,配置映射后,您更改为:
belongs_to :actor, polymorphic: true
转为新格式:
belongs_to :actor, polymorphic: true, integer_type: true
【解决方案3】:
有两种方法。
首先很简单:
has_many :bars, :conditions => "whatever you want"
第二个可能很棘手:
set_inheritance_column :bar_type_id
【解决方案4】:
我不确定,但你可以玩玩
belongs_to :bar, :class_name => proc{ BarType.find(self.bar_type_id).name }, :foreign_key => :bar_id