2012-04-12 55 views
0

這將顯示在邊欄中,這就是爲什麼我把它放在應用程序控制器中。即時開出了更好的解決方案我只想顯示按tag.resources.count排序的最新10個標籤

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> 

我不此刻有多少代碼(希望其在正確的位置)...我真正想做的是顯示最受歡迎的10個標籤,按tag.resources.count排序,以及按日期排序的最新5個標籤。我試圖四處尋找find(:order =>),但事實證明這毫無益處。

有沒有一種神奇的方式來做到這一點?由於

回答

1

與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 

這樣開始,到ActiveRecordize這...

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") 

稱這種由:

Tag.by_most_resources.limit(10) 
+0

這是同爲sqlite3的? – Tallboy 2012-04-12 21:06:09

+0

SQLite3 :: SQLException:接近「*」:語法錯誤:SELECT「tags」。* FROM「tags」INNER JOIN資源ON resources.tag_id = tags.id GROUP BY標記。* ORDER BY count(resources.id)DESC LIMIT 10 – Tallboy 2012-04-12 21:07:24

+0

有什麼想法?我覺得我很親密,因爲這是一個很好的答案:/ – Tallboy 2012-04-12 23:58:12