作者对象has_many文章, 根据发布文章的多少对作者进行排序, 实现好似简单, 而在rails中,有什么的好的写法?
共收到 19 条回复
楼主自己的想法是?
将 articles_count 作 count_cache,加上数据库索引,并以此排序。
我这个办法有没有问题?我以前就是这么用的。。
Author.joins(:articles).select("count(articles.id) as article_count").group("authors.id").order("article_count")
2楼的办法还没见过。。一会儿研究一下
@Rei 就是实现一个文章发表排行榜!以数量为排名参考!
@ashchan 求代码!有点模糊
@cqpx 参考中!!!谢谢!!!
class Post
include Mongoid::Document
belongs_to :user, :counter_cache => true
end
class User
include Mongoid::Document
field :posts_count, :type => Integer
has_many :posts
index :posts_count
# 文章多的用户倒序排列
scope :hot, desc(:posts_count)
end
@hot_users = User.hot.limit(10)
这是 Mongoid 的写法,ActiveRecord 类似,转换一下就好了。
@huacnlee field :post_count, :type => Integer 这里不属于 activerecord>??
#14楼 @stephen CounterCache 在 Rails Guides 里面有介绍 http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache
#17楼 @stephen 这个看 Mongoid 的文档里面有介绍 http://mongoid.org/docs/querying/criteria.html#desc
#17楼 @stephen http://mongoid.org/docs/querying/criteria.html#desc 这是 mongoid 的写法,AR 找 order