Ruby/Rails Collection to Collection

前端 未结 4 1642
天涯浪人
天涯浪人 2021-02-09 23:04

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

Library
Book
LibraryBooks

What I need to do is if i have the id of a l

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 23:05

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

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

    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.

提交回复
热议问题