如何使用Rails include? [英] How to use Rails include?
问题描述
我有一个有很多订单的模型用户
I have a model user with many orders
class User < ApplicationRecord
has_many :orders, inverse_of: :user, dependent: restrict_with_exception
end
和模型顺序如下:-
Class Order < ApplicationRecord
belongs_to :user, inverse_of: :order
end
我想获取所有订单,但要在同一组中包含user.name和user.mobile之类的用户详细信息.在这种情况下如何使用包含?
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?
推荐答案
您可以通过以下提到的查询使用包含项:
You can use includes using the below mentioned query:
@users = User.where(id: 1).includes(:orders)
然后遍历@users并获取相应的用户并订购数据.
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")
在这种情况下,您将获得单个查询中的所有数据,而不会像includes那样将rails缓存db对象存储在内存中.
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.
这篇关于如何使用Rails include?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!