运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

ruby-on-rails – 如何解决ActiveStorage URL的N 1?

运维开发网 https://www.qedev.com 2020-08-13 10:27 出处:网络 作者:运维开发网整理
你如何用他们的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_on
你如何用他们的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 (Association named ‘avatar’ was not found on User; perhaps you misspelled it?)

执行时弹出相同的错误:

User.includes(:avatar)
对于名为avatar的单个附件,Active Storage会添加一个with_attached_avatar范围,用于预加载相关关联:

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

请参阅has_one_attached的API文档.

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消