これは私のモデルです:
class Tag < ActiveRecord::Base
# id, name
has_many :taggings
end
class Tagging < ActiveRecord::Base
# id, tag_id, owner_id, target_type, target_id
belongs_to :tag
belongs_to :owner, :class_name => 'User'
belongs_to :target, :polymorphic => true
validates_uniqueness_of :tag_id, :scope => [ :target_id, :target_type, :owner_id ]
end
class Asset < ActiveRecord::Base
# id, owner_id, title, type, etc
belongs_to :owner, :class_name => 'User'
has_many :taggings, :as => :target
has_many :taggers, :through => :taggings, :source => :owner, :uniq => true
has_many :tags, :through => :taggings, :uniq => true
end
class User < ActiveRecord::Base
# id, name, email, etc
has_many :assets, :foreign_key => 'owner_id'
has_many :my_taggings, :class_name => 'Tagging', :foreign_key => 'owner_id'
has_many :my_tags, :through => :my_taggings, :source => :tag, :uniq => true
has_many :taggings, :as => :target
has_many :taggers, :through => :taggings, :source => :owner, :uniq => true
has_many :tags, :through => :taggings, :uniq => true
end
すべての関係は機能していますが、解決策が見つからないという追加の要件があります。
Assetクラスでこの関係を検討してください
has_many :tags, :through => :taggings, :uniq => true
Asset.find( :first ).tags を呼び出すと、期待どおりにタグの配列が返されますが、:uniq => true が指定されていない場合に行が何回表示されるかを示す count 属性を各タグに含める必要があります。
例えば。複数のユーザーが同じタグをアセットに適用できます。タグ名と適用ユーザー数を表示したい。