加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 获取Rails中所有模型类型记录的所有相关数据?

发布时间:2020-12-17 02:23:59 所属栏目:百科 来源:网络整理
导读:如何合并获取给定模型的所有记录的所有相关数据? 我有以下型号: User --N:1-- Reservation --1:N-- Concert 所以伪代码: Reservation belongs_to UserReservation belongs_to ConcertUser has_many ReservationsUser has_many Concerts through Reservati
如何合并获取给定模型的所有记录的所有相关数据?

我有以下型号:

User --N:1--> Reservation <--1:N-- Concert

所以伪代码:

Reservation belongs_to User
Reservation belongs_to Concert
User has_many Reservations
User has_many Concerts through Reservations
Concert has_many Reservations
Concert has_many Users through Reservations

如何制作一大堆所有内容?

>我可以通过Reservation.all获得所有预订
>我可以通过Reservation.find(25).user获取特定预订的用户
>我可以通过Reservation.find(25).concert获得特定预订的音乐会

但我如何为所有人获得它呢?如果我做

Reservation.all.each do |res|
   res.user.name+","+res.concert.name+","+res.concert.date # etc.
end

然后,当它循环时,它将为每个预留执行两个新的数据库查询.对于10条记录,它可能无关紧要,但对于数千条记录来说,它可能会非常痛苦.添加其他协会(例如音乐会belongs_to场地,用户has_one电子邮件等)…

有没有办法说,“获取所有预订和以下附加信息”,以便它加载到一个SQL查询?

解决方法

您要完成的任务称为急切加载,可以使用ActiveRecord中的包含来完成.见下文:

N + 1 queries problem

Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the includes method of the Model.find call. With includes,Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

在您的示例中,您可以使用以下内容:

Reservation.all.includes(:user,:concert)

为:belongs_to关系指定:inverse_of选项也是一个好主意.这样可以优化对象加载,并确保交叉引用模型将指向内存中的同一对象,即:

@user == @user.reservations.first.user # true

更多信息请点击此处:

If you are using a belongs_to on the join model,it is a good idea to set the :inverse_of option on the belongs_to …

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

在你的例子中:

# app/models/reservation.rb

belongs_to :user,:inverse_of => :reservations
belongs_to :concert,:inverse_of => :reservations

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读