【问题标题】:Need help to understand :source_type option of has_one/has_many through of Rails需要帮助理解:通过 if Rails 的 has_one/has_many 的源类型选项
【发布时间】: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


    【解决方案1】:

    :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

    希望对你有帮助。

    【讨论】:

    • 这是一个很好的解释。你能以同样的方式向 docrails 项目提交一个补丁来解释它吗? github.com/lifo/docrails.
    • 谢谢!这个我找了好久!
    • 你的意思是它不知道在关系中加入哪种类。它会从taggings.map {|link| link.taggable} 中找出类的类型
    • 那么如何从标签中找到所有可标记的?我应该从标记中手动获取它吗?
    【解决方案2】:

    ☝?这条消息是关于上面的帖子 (我还没有足够的声誉将此添加为评论...)

    感谢@TheDelChop 提供了这个简单而完美的用例。我只是建议用这个描述你的用户故事的简单模式来完成你的完美解释。以防万一。 谢谢 !

    【讨论】:

    • 这个插图最好并入上一个答案。
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多