问题
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