gpt4 book ai didi

ruby-on-rails - 需要帮助来了解Rails的has_one/has_many的:source_type选项

转载 作者:行者123 更新时间:2023-12-03 09:02:02 25 4
gpt4 key购买 nike

在Rails 3.1中,文档说

“4.2.2.13:source_type

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


我只是阅读:source的说明,但仍然不知道source_type的用途是什么?

最佳答案

: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

希望能帮助到你。

关于ruby-on-rails - 需要帮助来了解Rails的has_one/has_many的:source_type选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9500922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com