Ruby on Rails 如何创建作用域查询无Active Storage附件的记录?
报错原因
Active Storage 的附件数据不会存储在你的业务表(此处为movies表)中,而是保存在框架自带的active_storage_attachments、active_storage_blobs两张独立表中,通过多态关联和Movie模型绑定,因此movies表本身不存在poster字段,直接写where(poster: nil)会触发字段不存在的报错。
正确作用域写法
分两种版本适配场景:
- Rails 6.1 及以上版本可直接使用框架内置的
missing方法,自动处理关联查询逻辑,写法最简洁:
scope :no_poster, -> { where.missing(:poster) }
- Rails 6.1 以下版本可手动写左外连接+空值判断逻辑实现:
scope :no_poster, -> { left_joins(:poster_attachment) .where(active_storage_attachments: { id: nil }) }
poster_attachment是has_one_attached :poster自动生成的关联,指向对应ActiveStorage::Attachment记录,筛选该关联ID为空即可匹配到未上传海报的电影记录。
内容的提问来源于stack exchange,提问作者tkhobbes
相关产品推荐
相关产品推荐

