gpt4 book ai didi

ruby-on-rails - 您如何为ActiveStorage URL解决N + 1?

转载 作者:行者123 更新时间:2023-12-04 10:22:55 24 4
gpt4 key购买 nike

您如何预加载所有记录及其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(在用户上找不到名为“ avatar”的关联;也许您拼错了?)


执行时会弹出相同的错误:

User.includes(:avatar)

最佳答案

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

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


请参阅 has_one_attached的API文档。

关于ruby-on-rails - 您如何为ActiveStorage URL解决N + 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51785703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com