【问题标题】:Rails ActiveStorage - has_on_attached/has_many_attached associations is load by defaultRails ActiveStorage - has_on_attached/has_many_attached 关联默认加载
【发布时间】:2018-12-04 19:12:17
【问题描述】:

我遇到了 ActiveStorage 的问题,目前我的模型上有 has_on_attachedhas_many_attached 关系

每次我调用我的模型时,它都会加载如下关系:

ActiveStorage::Attachment Load (4.2ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id", 4934], ["record_type", "User"], ["name", "profile_picture"], ["LIMIT", 1]]

ActiveStorage::Attachment Exists (0.9ms) SELECT 1 AS one FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id", 4934], ["record_type", "User"], ["name", "home_pictures"], ["LIMIT", 1]]

如何默认禁用此行为?

【问题讨论】:

标签: ruby-on-rails ruby rails-activestorage


【解决方案1】:

你可以使用Model.with_attached_images.find(:id)来避免N+1

https://github.com/rails/rails/tree/master/activestorage#examples

我不确定您是否可以禁用急切加载附件,但以上内容应该有助于清理一下。

【讨论】:

  • 谢谢,是的,我也找到了这个解决方案,它似乎有效;)
  • 我有同样的问题,但我使用的是连接。清单有许多附件。 School.joins(:listing).where('beds > ?',beds)。在这种情况下,我如何渴望加载附件,或者更好的是,根本不加载附件?
  • @tomb 您也许可以使用Model.select() 来限制包含/呈现的字段(也不包括with_attached... 语法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多