【问题标题】:Ruby on Rails: How can I create a scope that checks whether there is an attachment?Ruby on Rails:如何创建一个检查是否有附件的范围?
【发布时间】:2021-11-01 15:00:29
【问题描述】:

我有一个通过主动存储(has_one_attached :poster)带有“海报”附件的电影对象

我想创建一个范围来检索所有没有附加海报的电影,但是这里不起作用:

scope :no_poster, -> { where (poster: nil) }

这会导致错误提示

Unknown column 'movies.poster' in 'where clause'

(这对我来说很有意义:)

如何创建这样的范围?

【问题讨论】:

  • 您能补充一下您使用的是哪个 Rails 版本吗?
  • 当然 - 使用版本 6.1.4.1

标签: ruby-on-rails rails-activestorage


【解决方案1】:

如果有人搜索此内容,请在这里回答我自己的问题:engineersmnky 的评论是正确的,关系名称是 poster_attachment,所以为了创建一个搜索没有海报的电影的范围

scope :no_poster, -> { where.missing(:poster_attachment) }

【讨论】:

    【解决方案2】:

    Rails 6.1 adds 缺少在 ActiveRecord 中搜索孤立记录的查询方法。

    试试

    scope :no_poster, -> { where.missing(:poster_attachment) }
    

    【讨论】:

    • 不幸的是不起作用。我认为这与海报实际上不是模型中的一个字段这一事实有关......它是来自活动存储的附件......所以我理解为什么它说“未知列”......跨度>
    • @tkhobbes 尝试将其更改为 scope :no_poster, -> { where.missing(:poster_attachment) },因为这是由 has_one_attached 宏创建的实际关系名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2022-01-20
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多