这是一个图书馆系统,人们可以在这里借书。每本书都属于一个类别。我们想根据人们最常借的书种类给他们一些建议。
以下是四种型号:
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 方式编写查找器...
最佳答案
你可以做以下事情,在person.rb中写以下内容
has_many :books, :through => :borrows
has_many :categories_of_books, :through => :books, :source => :category
&
def suggested_books
Book.where("category_id IN (?) AND id NOT IN (?)", self.categories_of_books, self.books)
end
虽然它会导致 1 个以上的查询,但它很干净,您只需要执行以下操作:
@user.suggested_books
关于ruby-on-rails - 如何用几个子查询编写 Rails finder,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13488333/