Railsのhas_one/has_manyの:source_typeオプションを理解するのに助けが必要です。質問する

Railsのhas_one/has_manyの:source_typeオプションを理解するのに助けが必要です。質問する

Rails 3.1のドキュメントにはこう書かれています

"4.2.2.13 :ソースタイプ

:source_type オプションは、ポリモーフィック関連付けを経由する has_one :through 関連付けのソース関連付けタイプを指定します。"

私は今読んだ:ソース説明はありますが、source_type が何に使用されるのかまだわかりませんか?

ベストアンサー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」のタグが付けられたオブジェクトのコレクションしか取得できません。ソースのみを指定すると、オブジェクトがどの種類のクラスであるかがわからないため、DB 内のどのテーブルから取得するかがわかりません。source_type取得しようとしているオブジェクトのタイプを通知します。

これは、こちらのブログ投稿から引用したものです:http://www.brentmc79.com/posts/polymorphic-many-to-many-associations-in-rails

それが役に立てば幸い。

おすすめ記事