简体   繁体   English

如何从嵌套的activerecord集合中获取所有记录

[英]How to get all records from a nested activerecord collection

I have an ActiveRecord query that i need help with. 我有需要帮助的ActiveRecord查询。

Lets say we have a user and he has multiple libraries. 假设我们有一个用户,他有多个库。 In each library, there are many collections. 每个库中都有许多馆藏。 In each collection, he has many books. 在每个集合中,他都有很多书。

How do I get a list of all his books? 我如何获得他所有书籍的清单?

I know I can do libraries.each |library| 我知道我可以做library.each | library | library.collections.each do |collections| library.collections.each做|馆藏| collection.books.each do |book| collection.books.each做| book | books << book.title 书籍<< book.title

but I'm hoping for a simpler methodology then this. 但是我希望能有一个比这更简单的方法。

You can use rails' has_many through for it 您可以通过使用rails的has_many

class User
  has_many :libraries
  has_many :collections, through: :libraries
  has_many :books, -> { uniq }, through: :collections
end

Then you can simply query 然后您可以简单地查询

@user = User.first
@user_books = @user.books

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM