2012-02-29 124 views
20

的HAS_ONE /的has_many的SOURCE_TYPE選擇在Rails 3.1,該文件說,需要幫助理解:通過Rails的

「4.2.2.13:SOURCE_TYPE

的:SOURCE_TYPE選項指定一個HAS_ONE源關聯類型:通過關聯進行多態關聯。 「

我剛剛讀了:source的解釋,但仍然沒有得到什麼source_type用於?

回答

47

:source_type涉及多態的關聯。也就是說,如果你有這樣的關係:

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 

然後源類型,您可以進行查詢這樣的:

「查找我所有的已經標記與標籤的書籍名爲「玩轉」」

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

沒有源類型,您將無法做到這一點,你只能得到這都貼着有‘趣’對象的集合。如果你只指定源代碼,它不會知道對象是哪一類,所以你不知道數據庫中的哪個表需要從哪個表中提取。 source_type通知您嘗試檢索哪種類型的對象。

這是從這個博客帖子採取:http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails

希望它能幫助。

+4

這是一個很好的解釋。你能否以相同的方式向docrails項目提交一個補丁來解釋它? http://github.com/lifo/docrails。 – 2012-02-29 19:37:11

+0

謝謝!我一直在尋找這個很長一段時間! – 2014-04-25 10:51:16

+0

你的意思是它不知道關係中的連接類型。它會從'taggings.map {| link |'中找出類的類型link.taggable}' – 2018-01-09 20:51:16