Kamilski81
Kamilski81

Reputation: 15117

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

In Rails 3.1, the documentation says

"4.2.2.13 :source_type

The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association. "

I just read :source explanation but still dont get what source_type is used for?

Upvotes: 36

Views: 18842

Answers (2)

v2lrf
v2lrf

Reputation: 331

ā˜šŸ¼ 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

Upvotes: 8

TheDelChop
TheDelChop

Reputation: 7998

: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.

Upvotes: 82

Related Questions