Need help to understand :source_type option of has_one/has_many through of Rails

:source_type deals with associations that are polymorphic. That is to say, if you have a relationship like this:

class Tag < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy
  has_many :books, :through => :taggings, :source => :taggable, :source_type => "Book"
  has_many :movies, :through => :taggings, :source => :taggable, :source_type => "Movie"
end

class Tagging < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
  belongs_to :tag
end

class Book < ActiveRecord::Base
  has_many :taggings, :as => :taggable
  has_many :tags, :through => :taggings
end

class Movie < ActiveRecord::Base
  has_many :taggings, :as => :taggable
  has_many :tags, :through => :taggings
end

Then the source type allows you to make queries like this:

"Find me all of the books that have been tagged with the tag named 'Fun'"

tag = tag.find_by_name('Fun')
tag.books

Without source type, you wouldn't be able to do that, you could only get a collection of objects that were tagged with 'Fun'. If you only specificed source, it wouldn't know which kind of class the objects were, so you it wouldn't know which table in the DB to pull from. The source_type Informs it of which type of object you are trying to retreive.

This is taken from this blog post: http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails

Hope it helps.


☝🏼 this message is about the post above (I don't have enough reputation yet to add this as comment...)

Thanks @TheDelChop for that simple and perfect use case. I just propose to complete your perfect explanation with this simple schema which describe your user story. Just in case of. Thank you ! enter image description here