How to use Rails include?

╄→尐↘猪︶ㄣ 提交于 2019-12-13 10:53:54

问题


I have a model user with many orders

 class User < ApplicationRecord 
  has_many :orders, inverse_of: :user, dependent: restrict_with_exception
end

and a model order as follows :-

Class Order < ApplicationRecord
 belongs_to :user, inverse_of: :order
end

I want to fetch all orders but with details of user like user.name and user.mobile in same set. How do I use include in this case?


回答1:


You can use includes using the below mentioned query:

@users = User.where(id: 1).includes(:orders)

then iterate over @users and fetch the corresponding user and order data.

Also, you could use lazy loading as well using the below query:

@users = User.where(id: 3).joins(:orders => [:order_data]).select("orders.*, users.first_name")

In this you will be getting all the data in the single query without rails caching the db objects in memory as in the case of includes.



来源:https://stackoverflow.com/questions/50323598/how-to-use-rails-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!