views:

21

answers:

1

I need to read the number of times that tag_id shows up in the listings_tags db table. Tags are entered into the system via the Listings form. I have a page that lists just tags.

current

tag1()
tag2()
tag3()
tag4()

Desired

tag1(40)
tag2(22)
tag3(5)
tag4(4)

code that may be relevant

schema

  create_table "listings_tags", :id => false, :force => true do |t|
    t.integer "listing_id"
    t.integer "tag_id"
  end

  create_table "tags", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

class Tag < ActiveRecord::Base
  has_and_belongs_to_many :listings
  validates_uniqueness_of :name

class Listing < ActiveRecord::Base
  belongs_to :profile
  has_and_belongs_to_many :tags
A: 

First of all, the use of the has_and_belongs_to_many-Association is discouraged. It's better to use a join model:

class Tag < ActiveRecord::Base
  has_many :listings, :through => :listing_tagging
end

class Listing < ActiveRecord::Base
  has_many :tags, :through => :listing_tagging
end

class ListingTagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :listing
end

This would enable you to say something like:

ListingTagging.select("tag_id, COUNT(tag_id) as tagging_count")
              .group(:tag_id)
              .order("tagging_count DESC")
              .limit(10)
              .map { |t| [t.id, t.tagging_count] }
# => [[tag_id1, tagging_count_1], ... ]
flitzwald