如何解决ActiveStorage URL的N+1问题?

17

如何预加载所有记录及其URL?

以下是我在jbuilder中获取URL的代码:

# views/users/index.json.jbuilder
...
json.avatar_url user.avatar.attached? && rails_blob_url(user.avatar)
...


Comment
    has_one :user

User
    has_one_attached :avatar

如何预加载所有用户及其头像?


Comments.includes(users: :avatar)

执行后出现以下错误:

ActiveRecord::AssociationNotFoundError(在User上未找到名为“avatar”的关联,您可能拼写错误吗?)

执行以下命令时将出现相同的错误:

User.includes(:avatar)

你是为用户列表做这个吗?你能否附加一个位置,说明你从哪里获取这个用户列表的吗? - Nermin
@Nermin已添加。我想这就是你所要求的。 - Strawberry
user.avatar是什么,它与User有什么关系?从您的错误信息来看,似乎它不是一个关联。它是一个属性吗? - 3limin4t0r
@JohanWentholt 我刚刚添加了一个更新。 - Strawberry
1个回答

33

对于一个名为:avatar的附件,Active Storage添加了一个with_attached_avatar范围,预加载相关联的关联:

@users.with_attached_avatar.each do |user|
  # ...
end

请参阅API文档中的has_one_attached


11
我找到了!includes(users: :avatar_attachment)。感谢帮助! - Strawberry
11
@Strawberry,接近了。你需要使用includes(users: { avatar_attachment: :blob })来预加载blobs。 - George Claghorn
实际上,:avatar_attachment 对我很有效,显著减少了我的响应时间。 - Strawberry
3
一个等价的作用域被添加到了复数附件中,例如:@users.with_attached_highlights - George Claghorn
2
Rails 6文档@ https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_one_attached - Pascal
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接