Search code examples
ruby-on-railsrubyactiverecordpolymorphic-associationssingle-table-inheritance

Polymorphic association foreign_type sets ancestor type instead current, using STI class


I have

class Car < ActiveRecord::Base; end

class Porsche < Car
  has_many :page_items, :as=>:itemable, :dependent=>:destroy
end

I have to mention that I'm using a single table called cars which has a field type.

class PageItem<ActiveRecord::Base
  belongs_to :itemable, :polymorphic=>true
end

When I do

  a = PageItem.new
  a.itemable = Porsche.new
  a.itemable
  #<Porsche id: nil, type: "Porsche", name: nil, ..etc>

  a.itemable_type
  => "Car"

And it should be

  a.itemable_type
  => "Porsche"

Do anybody have an idea about this?

Update

According to bor1s's answer probably this is the right behaviour. So if is it, then my question is how can I set it to Porsche implicitly?


Solution

  • This is because Porshe is virtual model, it is not really exist in in database, it just has type field to know that it is Porshe. Maybe you should get rid of STI and use say type column to save Car model with type of Porshe and use scope to find porshes. I hope I helped you alittle.