使用整数ID类型字段的多态关联 [英] Polymorphic Assocations using Integer ID type fields

查看:103
本文介绍了使用整数ID类型字段的多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆