这是一个图书馆系统,人们可以在这里借书。每本书都属于一个类别。我们想根据人们借的最多的书来给他们一些建议。
这里有四个模型:
class Person < AR
has_many :borrows
end
class Borrow < AR
belongs_to :person
belongs_to :book
end
class Category < AR
has_many :books
end
class Book < AR
has_many :borrows
belongs_to :category
end
我写了 SQL 来找书
SELECT * FROM books WHERE category_id =
(SELECT category_id FROM books WHERE id IN
(SELECT book_id FROM borrows WHERE person_id =10000)
GROUP BY category_id ORDER BY count(*) DESC LIMIT 1)
AND id NOT IN
(SELECT book_id FROM borrows WHERE person_id =10000)
这似乎有效,但我想知道如何以 Rails 方式编写查找器......