需要帮助来理解:通过Rails的has_one/has_many的source_type选项

Kam*_*i81 29 ruby-on-rails

在Rails 3.1中,文档说

"4.2.2.13:source_type

:source_type选项指定has_one:through关联的源关联类型,该关联通过多态关联进行."

我刚读过:源解释但仍然没有得到source_type用于什么?

The*_*hop 65

: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
Run Code Online (Sandbox Code Playgroud)

然后源类型允许您进行如下查询:

"找到所有标有"Fun"标签的书籍

tag = tag.find_by_name('Fun')
tag.books
Run Code Online (Sandbox Code Playgroud)

如果没有源类型,您将无法执行此操作,您只能获得标记为"Fun"的对象集合.如果你只是特定的源代码,它就不知道对象是哪种类,所以你不知道数据库中的哪个表可以从中拉出来.该source_type通知内容的对象类型它的你正在尝试中检索.

这可以从这篇博文中找到:http: //www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails

希望能帮助到你.

  • 这是一个很好的解释.您是否能够以相同的方式向docrails项目提交补丁解释它?http://github.com/lifo/docrails. (5认同)

v2l*_*lrf 8

\xe2\x98\x9d 这条消息是关于上面的帖子的\n(我还没有足够的声誉来添加此评论......)

\n\n

感谢@TheDelChop提供的简单而完美的用例。我只是建议用这个描述您的用户故事的简单模式来完成您的完美解释。以防万一。\n谢谢!\n在此输入图像描述

\n