【发布时间】:2012-02-29 14:30:21
【问题描述】:
在 Rails 3.1 中,文档说
"4.2.2.13 :source_type
:source_type 选项指定 has_one :through 关联的源关联类型,该关联通过多态关联进行。 "
我刚刚阅读了:source 的解释,但仍然不明白 source_type 的用途?
【问题讨论】:
标签: ruby-on-rails
在 Rails 3.1 中,文档说
"4.2.2.13 :source_type
:source_type 选项指定 has_one :through 关联的源关联类型,该关联通过多态关联进行。 "
我刚刚阅读了:source 的解释,但仍然不明白 source_type 的用途?
【问题讨论】:
标签: ruby-on-rails
: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
如果没有源类型,您将无法做到这一点,您只能获得带有“Fun”标签的对象集合。如果您只指定来源,它不会知道对象是哪种类,因此您不会知道从数据库中的哪个表中提取。 source_type 通知它您尝试检索的对象类型。
摘自这篇博文:http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails
希望对你有帮助。
【讨论】:
taggings.map {|link| link.taggable} 中找出类的类型
☝?这条消息是关于上面的帖子 (我还没有足够的声誉将此添加为评论...)
感谢@TheDelChop 提供了这个简单而完美的用例。我只是建议用这个描述你的用户故事的简单模式来完成你的完美解释。以防万一。 谢谢 !
【讨论】: