gpt4 book ai didi

ruby-on-rails - 如何从 has_many :through relations with :uniq => true 获取行数

转载 作者:行者123 更新时间:2023-12-04 06:36:04 25 4
gpt4 key购买 nike

这是我的模型:

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 ,该行将出现多少次。

例如。多个用户可以将相同的标签应用于 Assets 。我想显示标签名称加上应用它的用户数量。

最佳答案

这应该完全符合您的要求。

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

就返回的行而言:group => :id 将返回与 :uniq => true 相同的集合,但它也允许您执行所需的计算。这个语句比 :uniq => true 更费力,所以我给了它一个不同的名字,允许你选择是获取带有分组计数的唯一标签,还是仅获取唯一标签列表。

上述语句将向返回的记录添加频率属性。通过method_missing 的魔力,您可以使用@tag.frequency 访问它。

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

将打印@asset 的每个标签的 id、名称和出现次数。

关于ruby-on-rails - 如何从 has_many :through relations with :uniq => true 获取行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2199338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com