Elliot
Elliot

Reputation: 13835

Eager loading in controller in rails 3

In my app, posts has many tags.

the tags are connected through a join table, join_tags

In my index view, which lists all the posts, I do something like so:

<% post.tags.each do |tag| %>
    <%= tag.name %>,                                
<% end %>

The problem here, is its hitting the database for each post to load the tags.

Is there a way to load all of the tags for these tasks once in the controller? Maybe through the @Posts var? I have a feeling its through eager loading?

Upvotes: 1

Views: 1228

Answers (2)

Keith Woody
Keith Woody

Reputation: 11

It would be helpful to see your controller code, but I think you're looking for something like:

@posts = Post.all(:include => :tags) 

Upvotes: 0

jpemberthy
jpemberthy

Reputation: 7533

Yes you can, and as you said, eager loading is the right way to achieve this, you may want to do something like this in your controller action:

def index
  @posts = Post.includes(:tags).all
end

Assuming you have the following relationships in your post model:

has_many :join_tags
has_many :tags, :through => :join_tags

It will save you the n+1 post-tag queries.

Upvotes: 4

Related Questions