Rails 1 对多的表怎么查询比较好

dbian · 2012年10月19日 · 最后由 dbian 回复于 2012年10月19日 · 2874 次阅读

请问各位大侠, 我有表 1:users,表 2:books。 每个 user 对应若干 books, 如果查询每个 user 的 books 数量排名,这个我知道有个 count_cache 可以做到, 如果我想查每个 user 在一个时间段的 books 数量,这个该怎么弄?

谢谢

user.books.where('created_at < ? and created_at > ?', time1, time2).count

依然是 count_cache,另外加 count 字段。

#1 楼 @fresh_fish #2 楼 @Rei ,谢谢,如果想靠这个参数对 user 做个排序的话,请问,有没有什么好的方法 User.order("???") 这个???填什么好?

#3 楼 @dbian 奥,关系数据库的话可以查出来。

Book.where("created_at > ?", 1.day.ago).group(:user_id).select("user_id, count(*) AS books_count").order("books_count DESC")

匿名 #5 2012年10月19日

时间段???图书管理系统,借书数量?

#5 楼 @help5305fff 恩,只是举个栗子。。

#4 楼 @Rei ,多谢多谢,搞明白了,用不到 count_cache

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