Ruby on rails - 如何将tag_cloud限制在前 20 名taggings_count



如何将tag_cloud限制为20个具有最高计数的标签?

[1] pry(main)> Tag.find(1)
  Tag Load (0.2ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT 1  [["id", 1]]
=> #<Tag:0x007fcae0cf88e0 id: 1, name: "test", taggings_count: 4>
[2] pry(main)> Tag.find(4)
  Tag Load (0.1ms)  SELECT  "tags".* FROM "tags" WHERE "tags"."id" = ? LIMIT 1  [["id", 4]]
=> #<Tag:0x007fcae0ca0ac8 id: 4, name: "test the comma", taggings_count: 0>
[3] pry(main)>
Started GET "/as
class Tag < ActiveRecord::Base
  has_many :taggings

标签.rb

scope :top_20, -> do
  limit(20) #This limits it to the 20 tags first made regardless of if those tags have since been deleted?
end

我们如何从带有taggings_count: 0tag_cloud中删除标签(这可能需要另一个 SO 问题)?如果您在这里回答,则奖励积分;)

_tags.html.erb

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
  <%= link_to tag.name, tag_path(tag), :class => css_class %>
<% end %>

如果您需要进一步的解释或代码来帮助您帮助我,请告诉我:-]

图式

  create_table "taggings", force: true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context",       limit: 128
    t.datetime "created_at"
  end
  add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
  add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
  create_table "tags", force: true do |t|
    t.string  "name"
    t.integer "taggings_count", default: 0
  end
  add_index "tags", ["name"], name: "index_tags_on_name", unique: true

这是代码:

scope :top_20, -> {
  where("taggings_count != 0").order("taggings_count DESC").limit(20)
}

相关内容

  • 没有找到相关文章

最新更新