【问题标题】:Relation passed to #or must be structurally compatible from Rails 5.1 to 5.2传递给 #or 的关系必须在结构上兼容 Rails 5.1 到 5.2
【发布时间】:2020-02-07 19:50:35
【问题描述】:

Rails 从 5.1 更新到 5.2 后,我的应用程序损坏了

错误是:Relation passed to #or must be structurally compatible, Incompatible values: [:create_with]):,我不明白出了什么问题。

问题来自这个范围

  scope :publication, -> do
    where.not(type: 'Content::Teaser').
      where.not(home_position: nil).
      or(
        Content::Teaser.where(
          id: Content::Teaser.select(:id).joins(:content).where(content: Content.publication)
        )
      )
  end

为什么会出现这个错误?

【问题讨论】:

  • 尝试使用Content::Teaser.joins......pluck(:id) 而不是select(:id)
  • 我尝试使用Content::Teaser.joins(:content).where(content: Content.publication).pluck(:id),但收到同样的错误
  • 您不必为子查询显式选择 id。你应该可以做到:or(Content::Teaser.joins(:content).where(Content.publication))。不要听那些告诉你使用 .pluck 的人 - 它被广泛误用,在许多情况下会产生性能问题,因为它会强制查询并将数据加载到 ruby​​ 中,而不是创建子查询。 .pluck 只应在您真正需要 Ruby 中的数据数组时使用 - 而不是构造查询。

标签: ruby-on-rails


【解决方案1】:
# scope should only really be used for one-liners as its just syntactic sugar 
# and hurts the readability of your code
def self.publication
  where.not(type: 'Content::Teaser').
    where.not(home_position: nil).or(
      # provided that Content.publication is a scope
      Content::Teaser.joins(:content).where(Content.publication) 
    )
  )
end

【讨论】:

  • ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins, :create_with] Content.publication 不是范围,是内容模型(枚举)的状态
猜你喜欢
  • 2021-01-22
  • 2021-10-24
  • 2019-06-26
  • 2017-04-06
  • 2018-02-25
  • 2019-12-16
  • 2022-11-24
  • 2017-03-11
  • 1970-01-01
相关资源
最近更新 更多