Rails 如何排序 ActiveRecord::Relation

anklos · 2014年10月12日 · 最后由 cisolarix 回复于 2014年10月13日 · 2215 次阅读
class Post
  has_many :comments
end
class Comment
  # 表里有name这一栏
  belongs_to :post
end

我想选出根据comments.size排序post,然后返回的类型是ActiveRecord::Relation. 写到这里写不下去了:Post.includes(:comments).order('comment.size DESC')。不知应该怎么在order里来表示排序。

类似还有如果我想选出某一个人的commentPost.includes(:comments).where('comment.name = ?', name)?

请教应该如何做?谢谢!

post 加 comments_count

#1 楼 @saiga 没看明白,你是说在 posts 表里加上comments_count然后就直接Post.order('comments_count DESC')?

那如何根据名字选出某一个人的 comment 呢?

#2 楼 @anklos 你应该是问了两个问题吧。抱歉我没看到第二个...

attr_accessor :name 这是啥?

#4 楼 @saiga 就是简单的说下数据表里有name

你前面说在 posts 表里加 comments_count 是我理解的意思吗?那每次有新的 comment 进来都要更新 2 个表?感觉有点累赘啊。

#5 楼 @anklos rails 已经做了 get/set,你再加上 attr_accessor,别人会以为 name 是虚拟属性...

一次更新 N 张表都是常有的事,两张表就别嫌麻烦啦

#6 楼 @saiga 不是嫌麻烦,是想找一个统一的解决方法。

#1 楼 @saiga #7 楼 @anklos counter_cache 应该是你这个问题的解决方案

需要 登录 后方可回复, 如果你还没有账号请 注册新账号