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

| 我有一个表
Foo
,该表具有一个名为belongs1ѭ的多态belongs_to关联。
foos
表具有标准
bar_id
列。但是,我没有一个基于字符串的“ 4”列,而是一个整数“ 5”列。该列引用表
bar_types
中的
id
列。
bar_types.name
保存着表示特定
bar
实例的类的类的名称。 Rails(理想情况下> = 2.3.10)是否允许这种类型的多态关联?     
已邀请:
我们通过在新模块中覆盖
association_class
方法并使用
:extend
选项将其包括在内来完成此操作。还创建了一个整数到字符串的映射哈希,以简化操作。 在“ 12”目录中或任何您喜欢的位置,创建一个文件并定义哈希
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
    

要回复问题请先登录注册