Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of the "_type" column with polymorphic associations in Rails

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

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

  t.references :slottable, :polymorphic => true

In app/models/slot.rb:

  belongs_to :slottable, :polymorphic => true

In app/models/configuration.rb:

  has_many :slots, :as => :slottable

In 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've misunderstood the use of the slottable_type column. Have I?

At present, in app/models/configuration.rb:

slot = Slot.find_or_create_by_slottable_id_and_slottable_type(self.id, "configuration")
like image 203
steven_noble Avatar asked Aug 09 '11 12:08

steven_noble


People also ask

What is polymorphic association in Rails?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

How is polymorphic association set up in Rails?

The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.


1 Answers

The slottable_type has to be Configuration and not configuration.

like image 167
Maurício Linhares Avatar answered Sep 19 '22 23:09

Maurício Linhares