2010-02-04 24 views
6

這是我的模型:怎樣才能獲得的has_many行數:通過與關係:uniq的=>真

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添加標籤返回的數組,但我需要爲每個標籤包含一個count屬性指示行將出現多少次如果:未指定uniq => true。

例如。多個用戶可以將相同的標籤應用於資產。我想顯示標籤名稱以及應用它的用戶數量。

回答

5

這應該做你想要的。

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

行而言返回:組=>:標識將返回設定爲相同的:uniq的=>真實的,但它也可以讓你完成你想要的計算。這種說法比uniq => true更加勞動密集,所以我給了它一個不同的名稱,允許您選擇是否使用分組計數獲取唯一標籤,或者只選擇唯一標籤列表。

上述語句將頻率屬性添加到返回的記錄。通過method_missing的魔力,您可以通過@ tag.frequency訪問它。

用法:

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

將打印編號,名稱,數量及每個標籤的@asset的發生。

+0

不錯。那裏有很多好的信息! – 2010-02-04 17:37:44

+0

不起作用。我必須刪除:joins =>:標記並添加一個:source =>:標記。以下工作完全符合要求 - has_many:tags_with_count,:through =>:taggings,:source =>:tag,:group =>「tags.id」,:select =>「tags。*,COUNT(\」taggings .id \「)AS頻率」.....如果沒有您的幫助,我不會找到這個所以我無論如何都接受您的答案。會很高興你可以編輯你的答案。 – 2010-02-05 09:04:26

+0

對不起。我應該抓住嵌套的引號,並需要源選項。解決方案已經編輯,以解決這些小錯誤。 – EmFi 2010-02-05 16:12:23

相關問題