Ruby on rails 我只想显示按tag.resources.count排序的最新10个标记
这将显示在侧边栏中,这就是为什么我将它放在应用程序控制器中。我有更好的解决办法Ruby on rails 我只想显示按tag.resources.count排序的最新10个标记,ruby-on-rails,ruby,ruby-on-rails-3,controller,Ruby On Rails,Ruby,Ruby On Rails 3,Controller,这将显示在侧边栏中,这就是为什么我将它放在应用程序控制器中。我有更好的解决办法 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_t
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
class ApplicationController
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
class标记:资源\u标记
可访问属性:名称
验证:name,:presence=>true,
:length=>{:within=>2..20},
:唯一性=>{:区分大小写=>false}
范围:由大多数资源提供,
联接(“resources.tag_id=tags.id上的内部联接资源”)。
组(“标记”。).order(“count(resources.id)DESC”)
结束
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%>()
我现在没有太多的代码(希望它也在正确的位置上)。。。实际上,我所要做的就是按tag.resources.count显示最流行的10个标签,以及按日期排序的最新5个标签。我试着四处寻找find(:order=>),但结果证明没有用
有什么神奇的方法可以做到这一点吗?谢谢从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
所以,要激活此记录
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")
sqlite3也是这样吗?sqlite3::SQLException:靠近“”:语法错误:选择“标记”。从“标记”内部连接resources.tag_id=tags.id按标记分组。*按计数排序(resources.id)描述限制10有什么想法吗?我觉得我很接近,因为这是一个很好的回答:/你没有搞乱选择,是吗?SELECT子句错误,因为它没有列出字段。您不需要链中的select方法调用。@Tallboy我想Markdown接受了您的评论,现在斜体的文本周围应该有两颗星。至于错误,我猜SQLite不支持
groupby标记。*
。请尝试改用分组方式标记.id
?
Tag.by_most_resources.limit(10)