これはサイドバーに表示されるので、アプリケーションコントローラーに配置します。より良い解決策を受け入れる
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>
現在、コードはあまりありません(うまくいけば、適切な場所にあります)...本当にやりたいのは、tag.resources.countでソートされた最も人気のある10個のタグと、最新の5個のタグを表示することです。日付でソート。find(:order =>)を探してみましたが、役に立たなかったことがわかりました。
これを行うための魔法の方法はありますか?ありがとう