Ruby/Rails 集合到集合 [英] Ruby/Rails Collection to Collection

查看:33
本文介绍了Ruby/Rails 集合到集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接表的两个表 - 这只是伪代码:

I have a two tables joined with a join table - this is just pseudo code:

Library
Book
LibraryBooks

我需要做的是,如果我有图书馆的 id,我想获取该图书馆拥有的所有书籍所在的所有图书馆.

What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.

因此,如果我有图书馆 1,图书馆 1 中有书籍 A 和 B,而书籍 A 和 B 在图书馆 1、2 和 3 中,是否有一种优雅的(单行)方式在 rails 中做到这一点?

So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?

我在想:

l = Library.find(1)
allLibraries = l.books.libraries

但这似乎不起作用.建议?

But that doesn't seem to work. Suggestions?

推荐答案

l = Library.find(:all, :include => :books)
l.books.map { |b| b.library_ids }.flatten.uniq

注意 map(&:library_ids)map { |b| 慢b.library_ids } 在 Ruby 1.8.6 中,在 1.9.0 中更快.

Note that map(&:library_ids) is slower than map { |b| b.library_ids } in Ruby 1.8.6, and faster in 1.9.0.

我还应该提到,如果你在那里使用 :joins 而不是 include,它会在同一个查询中找到图书馆和相关书籍,从而加快数据库时间.:joins 仅在图书馆有书籍时才有效.

I should also mention that if you used :joins instead of include there, it would find the library and related books all in the same query speeding up the database time. :joins will only work however if a library has books.

这篇关于Ruby/Rails 集合到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆