10

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.

Does Rails (ideally >=2.3.10) allow for this type of polymorphic association?

lulalala
  • 17,572
  • 15
  • 110
  • 169
Craig Walker
  • 49,871
  • 54
  • 152
  • 212
  • 2
    As far as it is not standart polymorphic association you should write it by yourself. – fl00r May 25 '11 at 21:45

4 Answers4

11

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
Pratik Khadloya
  • 12,509
  • 11
  • 81
  • 106
2

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
ChrisInEdmonton
  • 4,470
  • 5
  • 33
  • 48
0

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
apneadiving
  • 114,565
  • 26
  • 219
  • 213
0

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
fl00r
  • 82,987
  • 33
  • 217
  • 237