传递给#or的关系必须在结构上兼容。不兼容的值:[:引用] [英] Relation passed to #or must be structurally compatible. Incompatible values: [:references]
问题描述
我有两个查询,它们之间需要一个或
,即我想要第一个或第二个查询返回的结果。
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)
第二个包含 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]
推荐答案
a href = https://github.com/rails/rails/issues/24055 rel = noreferrer>在Github上有关此问题的已知问题。
There is a known issue about it on Github.
根据此评论,您可能想覆盖 structurally_incompatible_values_for_or
以解决该问题:
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的关系必须在结构上兼容。不兼容的值:[:引用]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!