The relation passed in # or should be structurally compatible. Incompatible values: [: links]

I have two queries, I need or between them, that is, I want the results to be returned either by the first or second query.

The first request is a simple where() method that gets all the available elements.

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

The second includes join() and gives the current user elements.

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

I tried combining them with the 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 continue to encounter this error, and I am not sure how to fix it.

 Relation passed to #or must be structurally compatible. Incompatible values: [:references] 
+17
source share
2 answers

There is a known issue on Github .

According to this comment you can redefine structurally_incompatible_values_for_or overcome the problem:

 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 

There is also always the option to use SQL:

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

You can write a query in the old way to avoid error

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

Hope this helps!

+7
source

Source: https://habr.com/ru/post/1271862/


All Articles