views:

52

answers:

2

Newb question of the day:

I'm trying to select all the users with this condition, and then perform an action with each one :

User.find(:all).select { |u| u.organizations.count > 0} do |user|

Except, this isn't the right way to do this. Not entirely sure what the proper syntax is.

Any fellow rubyist offer a newb a hand?

+2  A: 

To perform an action with each element of a collection use the each method, like this:

User.find(:all).select { |u| u.organizations.count > 0}.each do |user|
sepp2k
+2  A: 

You'd probably be better folding the select into the query with:

User.find(:all, :conditions => "organization_id IS NOT NULL").each do |user|

This will only fetch the relevant results from the database so there should be less unnecessary data retrieved and thrown away.

EDIT: As suggested in the comments, the following would be correct for a many-to-many relationship assuming a join model called memberships (where user has_many :organisations, :through => :membership)...

User.all(:joins => "inner join memberships on memberships.user_id = users.id")
fd
`User.all(:conditions => "organisation_id is not null").each {|u| ...}` you mean?
Omar Qureshi
Yes, I fail by not thinking enough, you are quite right. Editing.
fd
@Omar: Since it's `organzations` and not `organization`, we can assume that the `user` table does not actually have an `organization` column, so that wouldn't work either.
sepp2k
Very true! in that case it would be a join to a organization_users (memberships?) table - on the assumption that it's M-to-M since that is the only thing that makes sense to me. Something like `User.all(:joins => "inner join memberships on memberships.user_id = users.id")`. No need for a count because by virtue of it having a record in the memberships table (and assuming that table has null constraints and proper RI) - it should *just work*
Omar Qureshi
@FD, In regards to your original Post FD, what kind of unneccessary data would be retrieved and thrown away if I went down sepp2k's route?I tried this and it returned "Mysql::Error: Unknown column 'organization_id' ". My user model says "has_many :organizations, :through => :organizations_users" ..Sorry, I'm daft. Should I be writing this differently? <br />Also! Sepp2k, and Omar, you guys are great. Thanks so much.
Trip
User.find(:all) will get every record from the database regardless of whether it matches the constraint in the select. I was attempting to offer an approach where only results matching the condition are retrieved from the database.
fd