我有2个型号:
class Books < ActiveRecord::Base
has_many :library_books
has_many :libraries, through: :library_books
end
class Library < ActiveRecord::Base
has_many :library_books
has_many :books, through: :library_books
end
我运行的查询类似于:
books = Book.joins(:libraries).where("title LIKE ?", "%somevalue%")
此查询可以运行并获取所有库中某个标题的所有书籍。但是,我试图从我拥有的书籍列表中获取所有库。如果我这样做,我可以得到每个图书馆:
books.each do |b|
libraries = b.libraries
# Do something with the libraries
end
然而,必须有一种更简单的方法来做到这一点,而不必遍历每本书。如何在不必遍历每本书的情况下获取所有库以获取查询(并删除可能显示的任何重复库)?有可能吗?
一如既往,提前谢谢!
答案 0 :(得分:1)
尝试:
libraries = Book.where("title LIKE ?", "%somevalue%").preload(:libraries).flat_map(&:libraries)
甚至更好:
libraries = Library.joins(:books).where("books.title LIKE ?", "%somevalue%").uniq
如果您需要书籍和图书馆:
books = Book.where("title LIKE ?", "%somevalue%").preload(:libraries)
libraries = books.flat_map(:libraries).uniq