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

dbian · October 19, 2012 · Last by dbian replied at October 19, 2012 · 2874 hits

请问各位大侠, 我有表 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")

Unknow user #5 October 19, 2012

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

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

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

You need to Sign in before reply, if you don't have an account, please Sign up first.