开发者

Eager loading in controller in rails 3

开发者 https://www.devze.com 2023-03-08 15:46 出处:网络
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:

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 controll开发者_运维知识库er? Maybe through the @Posts var? I have a feeling its through eager loading?


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消