Rails ActiveStorage scope for when file is attached

做~自己de王妃 提交于 2020-05-27 04:43:41

问题


When using ActiveStorage, how do you create a scope for when files are attached.

For example:

class Check < ActiveRecord::Base
  has_one_attached :image
end

I want something like Check.has_attached_image to return only records where there is an existing attached image.

I know that ActiveStorage provides a with_attached_image scope. But that doesn't seem to be working:

irb(main):009:0> Check.with_attached_image.to_sql => "SELECT \"checks\".* FROM \"checks\""


回答1:


Main purpose of the scope with_attached_image is to avoid N+1 queries (to include the attached blobs in your query).

To return only records where there is an existing attached image, you can create a scope in the Check model like this:

scope :has_attached_image, -> { joins(image_attachment: :blob) }



来源:https://stackoverflow.com/questions/53199420/rails-activestorage-scope-for-when-file-is-attached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!