问题描述
我有两个查询,我需要在它们之间使用 或
,即我想要第一个或第二个查询返回的结果.
I have two queries, I need an or
between them, i.e. I want results that are returned by either the first or the second query.
第一个查询是一个简单的where()
,它获取所有可用的项目.
First query is a simple where()
which gets all available items.
@items = @items.where(available: true)
Second 包含一个 join()
并提供当前用户的项目.
Second includes a join()
and gives the current user's items.
@items =
@items
.joins(:orders)
.where(orders: { user_id: current_user.id})
我尝试将这些与 Rails 的 or()
方法以各种形式结合起来,包括:
I tried to combine these with Rails' or()
method in various forms, including:
@items =
@items
.joins(:orders)
.where(orders: { user_id: current_user.id})
.or(
@items
.joins(:orders)
.where(available: true)
)
但我一直遇到这个错误,我不知道如何解决它.
But I keep running into this error and I'm not sure how to fix it.
Relation passed to #or must be structurally compatible. Incompatible values: [:references]
推荐答案
有一个已知问题它在 Github 上.
根据此评论,您可能想要覆盖在结构上不兼容_a> 克服这个问题:
According to this comment you might want to override the structurally_incompatible_values_for_or
to overcome the issue:
def structurally_incompatible_values_for_or(other)
Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } +
(Relation::MULTI_VALUE_METHODS - [:eager_load, :references, :extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } +
(Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") }
end
也总是有使用 SQL 的选项:
Also there is always an option to use SQL:
@items
.joins(:orders)
.where("orders.user_id = ? OR items.available = true", current_user.id)
这篇关于传递给#or 的关系必须在结构上兼容.不兼容的值:[:references]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!