views:

113

answers:

2

Disclaimer: My original exposure to Ruby on Rails was literally years ago, and a great many things are new to me now that I'm picking it back up. One of these things is named scopes. They seem great, but I'm not getting the result I expect. Here's a for-instance:

class User
  has_many logs
  named_scope :logged_in, :joins => ['logs'], :conditions => ['logs.logout_at IS NULL']
end

Class Log
  belongs_to user
end

It is my understanding that doing a

User.logged_in

should be exactly the same as doing a

User.find(:all, :joins => ['logs], :conditions => ['logs.logout_at IS NULL'])

But instead, I'm getting back different objects. To demonstrate:

real = User.find_by_name('admin')
  #<User id:12345, name: 'admin' ... >
fake = User.logged_in.find_by_name('admin')
  #<User id: 54321, name: 'admin' ... >

So my question is: Where on earth is this new object coming from, and how do I get named_scope to give me the original one?

A: 

It looks like you have multiple users named 'admin'

Try this:

User.find_all_by_name('admin')
wmoxam
Sadly, it's not the easy answer; that query returns exactly one result, the one I've labeled 'real' up there.
Atiaxi
+3  A: 
named_scope :logged_in, 
            :conditions => ["logs.logout_at IS NULL"], 
            :include => :logs
chap