Sam Saffron
Sam Saffron

Reputation: 131092

Rails eager loading, possible bug

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

Upvotes: 2

Views: 1151

Answers (2)

nitecoder
nitecoder

Reputation: 5486

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.

Upvotes: 0

Sam Saffron
Sam Saffron

Reputation: 131092

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.

Upvotes: 1

Related Questions