views:

447

answers:

2

In my Rails 2.3.2 app

I have 2 models:

class Post
   has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved => ?', true]
end

class Comment
  belongs_to :post
end

For some reason when I try to eager load my comments, I get an error

post = Post.find(:first, :conditions => ["permalink=?", permalink], :include => :approved_comments
undefined method `loaded?' for #

Coming from association_preload.rb line 228

Is this a known issue, or am I doing something wrong or unsupported?

I seem to find a little discussion about this at: http://groups.google.com/group/maine-ruby-users-group/browse_thread/thread/796cf58b62f9bc52

+1  A: 

FWIW,

I think I may have messed up here, I had approved_comments defined twice in my class. The unfortunate side effect I discovered was that eager loading plays up with that filtering and goes in to left join hell. So I worked around it by selecting everything and filtering in code.

Sam Saffron
A: 

You could try something like:

class Post
   has_many :approved_comments, :class_name => 'Comment'
end

class Comment
  belongs_to :post
end

and then something like:

Post.find(:all, :joins => :approved_comments, :conditions => ["comments.approved = ? AND permalink = ?", true, permalink], :include => :approved_comments)

This will find all the Posts that you want and then eager load the comments for them. In a large record set I would recommend against it though, it will be slow and blow out the memory size of your passenger/mongrel instance.

railsninja
yeah thats why I prefer the naked :include, the new eager loading will execute 2 queries, with a naked include, one for the comments and one for the post, which is much more memory friendly. This: http://www.samsaffron.com/archive/2008/03/15/You+should+be+very+careful+when+using+ActiveRecord+eager+loading is not totally fixed
Sam Saffron
Perhaps, I'm not a fan of naked include as it can very easily get out of control. That's why I don't mind this kind of thing, it's still only 2 queries but it definately only eager loads the records I need instead of loading everything and then deciding what it needs.
railsninja