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

Cra*_*ker 9 ruby-on-rails polymorphic-associations ruby-on-rails-2

我有一个表Foo有一个多态的belongs_to关联调用bar.该foos表具有标准bar_id列.但是,bar_type我有一个整数bar_type_id列,而不是基于字符串的列.此列引用id表中的列bar_types.bar_types.name保存表示特定bar实例的类的类的名称.

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

Pra*_*oya 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
Run Code Online (Sandbox Code Playgroud)

在comments.rb中

belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt
Run Code Online (Sandbox Code Playgroud)