Search code examples
ruby-on-railsmodelhas-many

ruby on rails manys' many


I am wondering how to do this without double each loop. Assume that I have a user model and order model, and user has_many orders.

Now I have a users array which class is User::ActiveRecord_Relation

How can I get the orders of these users in one line?


Solution

  • Actually, the best way to do that is :

    users.includes(:orders).map(&:orders)
    

    Cause you eager load the orders of the users (only 2 sql queries)

    Or

    Order.where(user_id: users.pluck(:id))
    

    is quite good too in term of performance