Cannon Moyer
Cannon Moyer

Reputation: 3164

"Or" statement not working in Rails Query

I have the following model structure:

class Job < ApplicationRecord
     belongs_to :location
     has_and_belongs_to_many :users
end

class Location < ApplicationRecord
     has_and_belongs_to_many :users
     has_many :jobs
end

class User < ApplicationRecord
    has_and_belongs_to_many :locations
end

This allows me to create jobs for a given location, and then associate/assign users to that job. My user table has an active attribute and I am getting an error when I try to query users that are either already assigned to the job or have a status of active. Here is my query:

@users = @job.location.users.where(users: { id: @job.user_ids }).or(@job.location.users.where(active: true))

The error:

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

Thanks in advance.

Upvotes: 5

Views: 3648

Answers (1)

Mark
Mark

Reputation: 6445

I think this should work:

@users = @job.location.users.where(id: @job.user_ids).or(@job.location.users.where(active: true))

Upvotes: 5

Related Questions