加载时检测到 Rails eager loading

Rails eager loading detected when loading

提问人:Romeo 提问时间:4/22/2023 最后编辑:Romeo 更新时间:4/22/2023 访问量:89

问:

我在加载页面时遇到这些错误。

USE eager loading detected
  Notification => [:actor]
  Add to your query: .includes([:actor])
Call stack
  .../views/api/notifications/index.json.jbuilder:6

USE eager loading detected
  Notification => [:notifiable]
  Add to your query: .includes([:notifiable])
Call stack
  .../views/api/notifications/index.json.jbuilder:9

在我看来,/views/api/notifications/index.json.jbuilder

json.new_notification_count @new_notification_count
json.next_page @notifications.next_page
json.notifications do |json|
  json.array! @notifications do |notification|
    json.id notification.id
    json.actor notification.actor.username
    json.actor_avatar_img_tag avatar_of(notification.actor, size: 40)
    json.action notification.action
    json.type notification.notifiable.class.to_s.underscore.humanize.downcase
    json.url case notification.notifiable.class.to_s
              when "Post" then post_path(notification.notifiable)
              when "User" then user_path(notification.notifiable)
              when "Response" then post_path(notification.notifiable.post, anchor: "response_#{notification.notifiable.id}")
              when "Message" then conversations_path(notification.notifiable)
              when "Order" then order_path(notification.notifiable)
             end
    json.time_ago time_ago_in_words(notification.created_at) + " ago"
    json.unread notification.read_at.nil?
  end
end

在我的控制器中

def index
    @notifications = Notification.where(recipient: current_user)
                                 .recent.paginate(page: params[:page], per_page: 8)
    @new_notification_count = Notification.where(recipient: current_user, is_new: true).count
end

在我的模型中

belongs_to :recipient, class_name: "User"
belongs_to :actor, class_name: "User"
belongs_to :notifiable, polymorphic: true

scope :pristine, -> { where(is_new: true) }
scope :recent, -> { order(created_at: :desc) }
scope :unread, -> { where(read_at: nil) }

这是一个示例脚本。

      Notification.create(recipient: receiver, 
                          actor: current_user, 
                          action: "sent you the ", 
                          notifiable: @message, 
                          is_new: true
                         )

我的项目上没有 Bullet gem。谁能建议我如何解决这个问题?

json ruby-on-rails 急切加载

评论

0赞 max 4/22/2023
您确定您实际上没有安装 Bullet 或其他 gem 吗?无论如何,警告是合法的。由于您不急于加载,因此您将获得 N+1 查询。您还可以通过使用并仅处理无法从模型派生路线的情况来清理这个臭味的案例语句。notifiablepolymorphic_path(notification.notifiable)
0赞 Romeo 4/22/2023
现在我可以通过更新控制器来修复它@notifications = Notification.includes(:actor).includes(:notifiable).where(recipient: current_user).recent.paginate(page: params[:page], per_page: 8)
0赞 lain0 5/18/2023
对于 abit 优化,将控制器计数更改为大小方法@new_notification_count = Notification.where(recipient: current_user, is_new: true).size

答: 暂无答案