eager loading a specific field?

so I am loading 100 posts, and know I will need post.author.name, is there a way to eager load just authors.name rather than all of authors' fields? thx

You can always use find_by_sql to load just what you want.

Something like:

  Posts.find_by_sql("select posts.*, author.name as author_name from posts join authors on post.author_id = author.id")

The Post records that are returned will have an @author_name attribute.

In general, I think find_by_sql should be avoided, as ActiveRecord should be used. But when there's a performance issue, you do what you have to do.

///ark

so I am loading 100 posts, and know I will need post.author.name, is there a way to eager load just authors.name rather than all of authors' fields? thx

You can always use find_by_sql to load just what you want.

Something like:

Posts.find_by_sql("select posts.*, author.name as author_name from posts join authors on post.author_id = author.id")

The Post records that are returned will have an @author_name attribute.

You can do the same without find by sql : Post.find :all, :joins
=> :author, :select => 'posts.*, authors.name as author_name'

Fred

rubynuby wrote:

so I am loading 100 posts, and know I will need post.author.name, is there a way to eager load just authors.name rather than all of authors' fields? thx

As Mark and Fred have pointed out, this can be done with a join and a custom select.

However in other cases where you wish to preserve the object hierarchy, and also ensure fields are converted to the correct Ruby type, you can try this plugin/monkey-patch:

http://dev.rubyonrails.org/attachment/ticket/7147/init.5.rb

Using this you would write:

Posts.find(:all, :conditions => '...', :include => :author[:name])