UNIQ =>真:との関係を通じて:どのようにしてにhas_manyから行数を取得することができます

StackOverflow https://stackoverflow.com/questions/2199338

質問

これは私のモデルです。

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
関係のすべてが働いているが、私は、私はのための解決策を見つけることができないという追加の要件があります:

資産クラスで、この関係を考える

has_many :tags, :through => :taggings, :uniq => true

Asset.findを呼び出す(:最初は)期待通りに返しますタグの配列を.tagsが、私は場合は、行が登場していた回数を示すカウント属性含むように、各タグのために必要があります。UNIQ =>真が指定されていませんでしたが。

など。複数のユーザが資産に同じタグを適用することができます。私は、タグ名に加えて、それを適用するユーザーの数を表示したいと思います。

役に立ちましたか?

解決

これは、あなたが望む正確に何をすべき。

has_many :tags_with_count, :source => :tag, :through => :taggings, 
  :group => "tags.id", :joins => :taggings,
  :select = "tags.*, COUNT('taggings.id') AS frequency"
行の面では、

は返さ:グループは=>:idが同じセットを返します。UNIQ => trueの場合、それはまた、あなたが欲しい計算を実行することができます。この文は、より労働集約的である:私はあなたが彼らのグループ化されたカウントでユニークなタグを取得、または一意のタグのリストだけにするかどうかを選択することができ、それを別の名前を与えてくれたので、uniqのは=>真

上記のステートメントは、返されたレコードに周波数属性を追加します。 method_missingの魔法を通じて、あなたはtag.frequency @とそれにアクセスすることができます。

使用方法:

@tags = @asset.tags_with_count
@tags.each{|tag| puts [tag.id, tag.name. tag.frequency].join "\t"}

のID、名前、および@asset各タグの出現回数を出力します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top