Lazy loading issue (I think) - what's up with this ?

I have three models:
(1) Mood
(2) User
(3) Mymood

Mymood belongs_to mood
Mymood belongs_to user

User has_many mymoods

I have a function in User, like this:

def moods
  if mymoods.empty?
    []
  else
    mymoods.collect{|mm| mm.mood}
  end
end

In Rails2, User.first.moods returns an array of moods (or an empty
array where there are none)

In Rails3, I get a big old error: uninitialized constant Mymood::Mood

I'm guessing it's something to do with lazy loading, because if I call
(in the console)
User.first.mymoods
then
  User.first.moods
it all works as it should, but if I just call on its own:
  User.first.moods
I get the error above

Any guidance gratefully received!

Look at things in the debugger, but the likelihood is that you're
trying to operate on what you think is an array of records, but is
just a query.

my_moods = MyMood.where("my criteria")

my_moods.collect.... Error

then my_moods.all.collect.... and you're good to go.

or my_moods = MyMood.where("my criteria").all
and my_moods.collect...

Thanks, Ray. Per your suggestion, this fixed it:

  def moods
    ms=Mymood.where('user_id=?',user_id)
    if ms.empty?
      []
    else
      ms.collect{|mm| mm.mood}
    end
  end

But it seems strange to have to write another query in the middle of a
model. I'd have thought that the "has_many :mymoods" in the user model
would have been enough.

Whatever. It's working now. Thanks for your help!

Of course, as I just discovered, if I'd put in

has_many :moods, :through=>:mymoods

that would have worked too :slight_smile: