cjm2671
cjm2671

Reputation: 19456

Simple rails :has_many 'none' query?

I'm trying to do the following:

I've got a relation:

User :has_many TeamMemberships

I found what to find all the users that have no team_memberships.

I've got the following:

User.all.each do |u|
  if u.team_memberships.nil?
    puts u.id
  end
end

But it doesn't seem to be working; am I missing something?

Upvotes: 0

Views: 52

Answers (1)

Max Williams
Max Williams

Reputation: 32933

When there are no associated objects, it will return an empty array, not nil. Try .blank? instead.

BTW, shouldn't it be

has_many :team_memberships

?

Btw2, here's a nicer way to get all the users who have no team_memberships:

users = User.find(:all, :include => [:team_memberships], :conditions => ["team_memberships.id is null"])

Upvotes: 1

Related Questions