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。
例如。多個用戶可以將相同的標籤應用於資產。我想顯示標籤名稱以及應用它的用戶數量。
不錯。那裏有很多好的信息! – 2010-02-04 17:37:44
不起作用。我必須刪除: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
對不起。我應該抓住嵌套的引號,並需要源選項。解決方案已經編輯,以解決這些小錯誤。 – EmFi 2010-02-05 16:12:23