Polymorphic Assocations using Integer ID type fields

有些话、适合烂在心里 提交于 2019-11-29 09:52:56

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.

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

In comments.rb

belongs_to :commentable, :polymorphic => true, :extend => CommentObjectType::ClassNamesAsInt

I'm making use of the polymorphic integer type gem, written by one of my co-workers. It's slightly easier to use than the examples given above, in my opinion. For example, after configuring the mapping, you change from:

belongs_to :actor,              polymorphic: true

to the new format:

belongs_to :actor,              polymorphic: true, integer_type: true

There are two approaches for this.

First is easy:

has_many :bars, :conditions => "whatever you want"

Second could be tricky:

set_inheritance_column :bar_type_id

I am not sure, but you can play around

belongs_to :bar, :class_name => proc{ BarType.find(self.bar_type_id).name }, :foreign_key => :bar_id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!