Using the _type Column with Polymorphic Associations in Rails

I have a Slot model belonging to a configuration model, as well as another model:

In db / migrate / ... create_slots.rb:

t.references :slottable, :polymorphic => true 

In the app /models/slot.rb:

  belongs_to :slottable, :polymorphic => true 

In the application /models/configuration.rb:

  has_many :slots, :as => :slottable 

In the rails console, I get:

  ruby-1.9.2-p180 :009 > Slot.last => #<Slot id: 69, slottable_id: 35, slottable_type: "configuration", number: 2, usage: "1GB 667MHz DDR2 SDRAM PC2-5300 SO-DIMM", created_at: "2011-08-09 12:12:25", updated_at: "2011-08-09 12:12:25"> ruby-1.9.2-p180 :009 > Slot.last.slottable NameError: wrong constant name configuration 

The only explanation I can come up with is that I misunderstood the use of the slottable_type column. I have?

Currently in app / models / configuration.rb:

 slot = Slot.find_or_create_by_slottable_id_and_slottable_type(self.id, "configuration") 
+7
source share
1 answer

The value of slottable_type should be Configuration , not .

+11
source

All Articles