0

I have researched a lot and I can't find the answer for my question. I have the following setup on my Rails app:

class Group < ActiveRecord::Base
  has_many :people
  # ...
end

class City < ActiveRecord::Base
  has_many :people
  # ...
end

class Person < ActiveRecord::Base
  belongs_to :city
  belongs_to :group
  # ...
end

The people have the column :role that is 0 or 1.

I want to get all the groups that have at least one person with role == 0 and one person with the role == 1.

Any idea? I'm using Postgres by the way.

1 Answer 1

1

Here's a query I just tested on my SQLite3 database (should work on Postgres too I believe):

 Group.select("groups.*").joins("LEFT JOIN people on groups.id = people.group_id").where("people.role==0 OR people.role==1").group("id")

Here I assume you've already added the foreign key group_id in your people migration. Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.