【问题标题】:Tagging from Scratch: the Tag Cloud Issue从头开始标记:标签云问题
【发布时间】:2012-10-09 19:09:21
【问题描述】:

我正在按照http://railscasts.com/episodes/382-tagging 的说明从头开始构建标签系统。一切都很好,但不是 tag_cloud 助手。搜索 tag_counts 时引发数据库错误。

以下范围:

#Picture.rb

class Picture < ActiveRecord::Base

  attr_accessible :description, :title, :tag_list

  has_many :taggings
  has_many :tags, through: :taggings

#Because of the following I'm getting an error from the Posgresql (showed in "Database Error")

  def self.tag_counts 

    Tag.select("tags.*, count(taggings.tag_id) as count").
      joins(:taggings).group("taggings.tag_id")
  end
end

Application_helper.rb

def tag_cloud(tags, classes)
  max = tags.sort_by(&:count).last
  tags.each do |tag|
    index = tag.count.to_f / max.count * (classes.size - 1)
    yield(tag, classes[index.round])
end

数据库错误

ActiveRecord::StatementInvalid in Pictures#index

PG::Error: column "tags.id" ​​should appear in the GROUP BY clause or be used in an aggregate function

LINE 1: SELECT tags.*, count(taggings.tag_id) as count FROM "tags" I...

               ^
: SELECT tags.*, count(taggings.tag_id) as count FROM "tags" INNER JOIN "taggings" ON "taggings"."tag_id" = "tags"."id" GROUP BY taggings.tag_id

【问题讨论】:

    标签: ruby-on-rails tagging tag-cloud


    【解决方案1】:

    您应该按 tags.id 分组,和/或计数 taggings.id

    Tag.select("tags.*, count(taggings.id) as count").
      joins(:taggings).group("tags.id")
    

    您不能在查询中同时分组和聚合。

    【讨论】:

    • 查询数据库的工作似乎完成了,谢谢! (Obrigado -> Português Brasileiro)但它返回一个 String 对象给 Application_helper.rb 中上面列出的 Helper Method,我又遇到了另一个问题:**TypeError in Pictures#index**String can't be coerced into Float
    • 这是一个单独的问题。将预期结果和实际结果放在一个新问题中(或任何有意义的隔离问题),以便每个人都有机会解决它。数据库错误已经消失,所以这个问题已经结束了。
    • 谢谢,没关系!我今天早上做对了。这条线index = tag.count.to_f / max.count * (classes.size - 1) 应该是max.count.to_i。太明显了!
    • 只需在 stackoverflow.com/questions/12820413/…> 上发布一个新问题,我觉得您可以提供帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多