我的一些类:Mongoid预先加载嵌入文档
class User
embeds_many :notifications
field :first_name
field :last_name
def name{ "#{first_name} #{last_name}" }
class Notification
embedded_in :user
belongs_to :sender, class_name: "User", inverse_of: nil
现在,在我的意见,我实现了一个较小的邮箱系统通知。但是,它目前打N +数据库1次:
<% current_user.notifications.sort{...}.each do |notif|%>
...
<%= notif.sender.name if notif.sender %>
这里的问题是,这将导致数据库N
命中notif.sender.name
。我能以某种方式预加载/急切加载吗?类似于current_user.notifications.includes(:sender)
(但可以工作:D)
我目前只需要发件人姓名。
哈哈,其实我的问题是风马牛不相及。我有一个奇怪的错误“错误的参数数量......”:工作查询是'current_user.notifications.includes(:sender).to_a.sort'。 'to_a'在这里很重要! – 2015-04-07 23:34:23
@CyrilDD它可能执行得更好,如果你想在你的查询中包含排序,而不是在本机数组上进行ruby排序 – ericraio 2015-04-30 02:54:58