Jul
Jul

Reputation: 151

Rails: Make database query using includes, where and OR

In my Rails app a database record from an Activity can have a relationship with usecases or masks. When at least one of these relations is missing, the record should be show on a view. I created following queries, but failed trying to concatenate them with OR, getting an "Relation passed to #or must be structurally compatible. Incompatible values: [:includes]" error. Here are the queries I am trying to concatenate with OR:

Activity.includes(:activities_usecases).where(:project_id => current_user.project_id, :activities_usecases => { :activity_id => nil })
Activity.includes(:activities_masks).where(:project_id => current_user.project_id, :activities_masks => { :activity_id => nil })

How does .or() needs to be used to make this work? I do not want the record with the missing conncetion(s) being shown twice, when both connections are missing, only once.

Upvotes: 0

Views: 106

Answers (1)

Siim Liiser
Siim Liiser

Reputation: 4348

Add the includes later or add them to both.

Activity.where(:activities_usecases => { :activity_id => nil }).or(
  Activity.where(:activities_masks => { :activity_id => nil })
).includes(:activities_usecases, :activities_masks).where(:project_id => current_user.project_id)

Upvotes: 1

Related Questions