0

タグ付け用のテーブルが2つあるので、どのモデルにもタグを付けることができます。そのように機能します…</ p>

tag_id列と、ポリモーフィズム用の他の2つの列(taggable_typeとtaggable_id…</ p>)を持つタグ付きアイテム結合テーブルがあります。

class TaggedItem < ActiveRecord::Base
  attr_accessible :taggable_id, :taggable_type, :tag_id

  belongs_to :taggable, :polymorphic => true
  belongs_to :tag
end

タグを付けることができるものもすべてあります。たとえば、タグが付いた商品と画像のモデルは次のとおりです。

class Product < ActiveRecord::Base
  has_many :tagged_items, :as => :taggable, :dependent => :destroy
  has_many :tags, :through => :tagged_items
end

class Image < ActiveRecord::Base
  has_many :tagged_items, :as => :taggable, :dependent => :destroy
  has_many :tags, :through => :tagged_items
end

問題はタグモデルにあります。逆の作業が行われるようです。タグモデルでは、has_many画像とhas_many製品を次のように使用します。

class Tag < ActiveRecord::Base
  has_many :tagged_items, :dependent => :destroy
  has_many :products, :through => :tagged_items
  has_many :images, :through => :tagged_items
end

これによりエラーが発生します。どうすれば修正できるのでしょうか。したがって、タグテーブルは多態的なタグ付きアイテムテーブルを介して機能します。

どんな助けでも大歓迎です。ありがとう!

編集:

Could not find the source association(s) :product or :products in model TaggedItem. Try 'has_many :products, :through => :tagged_items, :source => <name>'. Is it one of :taggable or :tag?
4

2 に答える 2

1

has_many :throughタグモデルの関連付けは、モデルのソース関連付けProductを取得できません。たとえば、TaggedItemで直接の関連付けを検索します。これは、ポリモーフィックな関連付けの場合は。として記述されます。したがって、タグモデルが関連付けの正確なソースを理解するには、オプションとそのタイプを次のように追加する必要があります。ImageTaggedItemhas_many :products, :through => :tagged_itemsbelongs_to :productbelongs_to :taggable, :polymorphic => true:source:source_type

したがって、タグモデルの関連付けを次のように変更します

class Tag < ActiveRecord::Base
  has_many :tagged_items, :dependent => :destroy
  has_many :products, :through => :tagged_items, :source => :taggable, :source_type => 'Product'
  has_many :images, :through => :tagged_items, :source => :taggable, :source_type => 'Image'
end

これで問題が解決するはずです。:)

于 2013-02-11T20:04:14.433 に答える
0

asTaggedItemへのタグの関連付けを設定するときにオプション は必要ありません。:as => :taggableタグ付けされたアイテムのタグは多形であり、そうではないことを意味します。代わりに、反対側は、つまり、あなたの名前が巧みに示唆しているようにタグ付け可能なアイテムです:)。

class Tag < ActiveRecord::Base
  has_many :tagged_items, :dependent => :destroy
  has_many :products, :through => :tagged_items
  has_many :images, :through => :tagged_items
end
于 2013-02-11T16:19:33.240 に答える