【问题标题】:ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins]ArgumentError:传递给#or 的关系必须在结构上兼容。不兼容的值:[:joins]
【发布时间】:2018-02-25 04:10:04
【问题描述】:

我在一个模型中有两个范围。两者都使用joinsjoins 似乎与 Rails 5 或查询不兼容。

例子:

class Blog < ApplicationRecord

  has_many :comments

  scope :with_comment_likes, -> {joins(:comments).merge(Comment.some_scope_on_comment)}
  scope :some_other_comment_merge_scope, -> {joins(:comments).merge(Comment.other_scope)}

  scope :aggregate_or_scope, -> {with_comment_likes.or(some_other_comment_merge_scope)}
end

Blog.aggregate_or_scope

返回错误:

ArgumentError: Relation passed to #or must be structurally compatible. 
Incompatible values: [:joins]

关于如何解决这个问题的任何建议?我难住了。我确实看到了this question,但我无法应用它。

【问题讨论】:

  • 您使用的是什么版本的 Rails?无法在 5.1.4 上重现此错误(可能已经修复)
  • 我确信它是 5.1.0 之前的 Rails 版本。
  • 这仍然发生在 Rails 6 中。

标签: ruby-on-rails ruby


【解决方案1】:

我遇到了同样的问题,我发现的解决方案是:

def matching_one_or_two temp = Model.matching_one + Model.matching_two Model.where('id in (?)',temp.map(&:id)) end

当然不是世界上最好的性能,但它会导致 ActiveRecord::Relation 对象指向“或”结果。

【讨论】:

    【解决方案2】:

    晚了两年,但您可以通过以下方式完成:

    class Blog < ApplicationRecord
    
      has_many :comments
    
      scope :aggregate_or_scope, lambda {
        joins(:comments).merge(
          Comment.some_scope_on_comment.or(Comment.other_scope)
        )
      }
    end
    
    Blog.aggregate_or_scope
    

    这里的区别在于您只加入一次,or 位于正在合并的 Comment 查询上,它没有任何 joins,而不是 Blog 查询。

    【讨论】:

      【解决方案3】:

      经过许多小径。这是可行的解决方案:

      def self.aggregate_or_scope
        with_comment_likes_id = with_comment_likes.pluck(:id)
        some_other_comment_merge_scope_id = some_other_comment_merge_scope.pluck(:id)
        all_ids = with_comment_likes_id.concat(some_other_comment_merge_scope_id)
        
        Blog.where(id: all_ids)
      end
      

      【讨论】:

        猜你喜欢
        • 2019-06-26
        • 2021-10-24
        • 2019-12-16
        • 2017-04-06
        • 2021-01-22
        • 1970-01-01
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多