Tallboy
Tallboy

Reputation: 13467

i just want to show the latest 10 tags sorted by tag.resources.count

this will show up in the sidebar, that is why i put it in application controller. im open to a better solution

class ApplicationController < ActionController::Base

  protect_from_forgery

  before_filter :get_tags_latest, :get_tags_popular

  def get_tags_latest
    @tags_latest = Tag.all.first(5)
  end

  def get_tags_popular
    @tags_popular = Tag.by_most_resources.limit(10)
  end

end

tag.rb:

class Tag < ActiveRecord::Base

  self.include_root_in_json = false

  has_many :resource_tags
  has_many :resources, :through => :resource_tags

  attr_accessible :name

  validates :name, :presence => true,
                   :length   => { :within => 2..20 },
                   :uniqueness => { :case_sensitive => false }

  scope :by_most_resources,
    joins("INNER JOIN resources ON resources.tag_id = tags.id").
    group("tags.*").order("count(resources.id) DESC")

end

sidebar.html.erb

<ul class="tag-list">
    <% @tags_popular.each do |t| %>
      <li><%= link_to t.name, tag_path(t), :class => :tag %> (<%= t.resources.count %>)</li>
    <% end %>
  </ul>

I don't have much code at the moment (hopefully its in the right spot too)... really all I want to do is show the most popular 10 tags sorted by tag.resources.count, as well as the latest 5 tags sorted by date. I tried looking around for find(:order => ) but that proved unhelpful.

Is there a magical way to do this? Thanks

Upvotes: 0

Views: 62

Answers (1)

Marlin Pierce
Marlin Pierce

Reputation: 10089

Starting with the SQL

SELECT tags.*
FROM tags
  INNER JOIN resources ON resources.tag_id = tags.id
GROUP BY tags.*
ORDER BY count(resources.id) DESC
LIMIT 10

so, to ActiveRecordize this...

class Tag < ActiveRecord::Base
  scope :by_most_resources,
    joins("INNER JOIN resources ON resources.tag_id = tags.id").
    group("tags.*").order("count(resources.id) DESC")

call this by:

Tag.by_most_resources.limit(10)

Upvotes: 1

Related Questions