Skip to content

Instantly share code, notes, and snippets.

@mrjabba
Created January 27, 2011 04:52
Show Gist options
  • Save mrjabba/798086 to your computer and use it in GitHub Desktop.
Save mrjabba/798086 to your computer and use it in GitHub Desktop.
Find some users who are NOT in this group
#ActiveRecord scoped query left outer join users to members
scope :not_in_group, lambda { |group|
join_clause = User.send(:sanitize_sql_array,
["LEFT OUTER JOIN memberships ON memberships.user_id = users.id WHERE memberships.group_id is not ?", group ])
User.select("distinct(users.id), users.*").joins(join_clause)
}
@MrJaba
Copy link

MrJaba commented Jan 27, 2011

I might be oversimplifying, but it should be a little easier:

User.find(:all, :conditions => ["group_id != ?", 1], :joins =>[:groups])

@mrjabba
Copy link
Author

mrjabba commented Jan 27, 2011

Thanks! That would be much simpler. I will try and let ya know.

@MrJaba
Copy link

MrJaba commented Jan 27, 2011

I re-read your tweet and saw it was a has_many :through, and that's based on a has and belongs to many, so it might not work.

@mrjabba
Copy link
Author

mrjabba commented Jan 27, 2011

OK, so it doesn't seem to work for what I need.

Your query produces an inner join on memberships.
SELECT "users".* FROM "users" INNER JOIN "memberships" ON "users"."id" = "memberships"."user_id" INNER JOIN "groups" ON "groups"."id" = "memberships"."group_id" WHERE (group_id != 1)

Mine produces a left outer join, which is what I believed I needed.
SELECT distinct(users.id), users.* FROM "users" LEFT OUTER JOIN memberships ON memberships.user_id = users.id WHERE memberships.group_id <> 1 or memberships.group_id is null

My intent was to list all users who are not already members of this group and include members who are not in a group at all.

Thanks again for the suggestion.

@mrjabba
Copy link
Author

mrjabba commented Jan 27, 2011

Heh. Would have helped for me to read your second comment too :-) No worries. I'm just happy that I'm finally getting past all the basic Rails/ActiveRecord stuff and now actually modelling some useful data.

@MrJaba
Copy link

MrJaba commented Jan 27, 2011

Ah the "who are not in a group at all." changes it quite a bit, so you will need the left join, you're quite right :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment