传递给#or的关系必须在结构上兼容。 不兼容的值:

我有两个查询,我需要一个or它们之间,即我想要第一个或第二个查询返回的结果。

第一个查询是一个简单的where() ,它获取所有可用的项目。

 @items = @items.where(available: true) 

第二个包括join()并给出当前用户的项目。

 @items = @items .joins(:orders) .where(orders: { user_id: current_user.id}) 

我尝试以各种forms将这些与Rails’ or()方法结合起来,包括:

 @items = @items .joins(:orders) .where(orders: { user_id: current_user.id}) .or( @items .joins(:orders) .where(available: true) ) 

但我一直遇到这个错误,我不知道如何解决它。

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

在Github上有一个已知的问题 。

根据此注释,您可能希望覆盖structurally_incompatible_values_for_or以克服此问题:

 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的选项:

 @items .joins(:orders) .where( "orders.user_id = ? OR items.available = true", current_user.id ) 

您可以用这种古老的方式编写查询以避免错误

 @items = @items.joins(:orders).where("items.available = ? OR orders.user_id = ?", true, current_user.id) 

希望有所帮助!