Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the source_type for this polymorphic association always 0?

For some reason the source type for a polymorphic has_many :through association is always 0, despite having set a :source_type.

Here's what my models look like...

Foo:

has_many :tagged_items, :as => :taggable
has_many :tags, :through => :tagged_items

Bar:

has_many :tagged_items, :as => :taggable
has_many :tags, :through => :tagged_items

TaggedItem:

belongs_to :tag
belongs_to :taggable, :polymorphic => true

Tag:

has_many :tagged_items
has_many :foos, :through => :tagged_items, :source => :taggable, :source_type => "Foo"
has_many :bars, :through => :tagged_items, :source => :taggable, :source_type => "Bar"

As near as I can tell that's a totally fine setup, and I am able to create / add tags, but the taggable_type always ends up being 0.

Any idea's why? Google has turned up nothing.

like image 428
hobberwickey Avatar asked Feb 27 '14 11:02

hobberwickey


1 Answers

Figured this one out myself, just answering because I'm sure I'm not the first or last person to make this stupid mistake (in fact I may have done it before). I put the column type on the taggable_type field as an integer instead of a string.

You'd think this might cause an error, but it doesn't. It just doesn't work.

like image 164
hobberwickey Avatar answered Sep 21 '22 16:09

hobberwickey