Not sure how to word the question concisely :).
I have say 20 Posts per page, and each Post has 3-5 tags. If I show all the tags in the sidebar (Tag.all.each...), then is there any way to have a call to post.tags not query the database and just use the tags found from Tag.all?
class Post < ActiveRecord::Base
end
class Tag < ActiveRecord::Base
end
This is how you might use it:
# posts_controller.rb
posts = Post.all
# posts/index.html.haml
- posts.each do |post|
render :partial => "posts/item", :locals => {:post => post}
# posts/_item.html.haml
- post.tags.each do |tag|
%li
%a{:href => "/tags/#{tag.name}"}= tag.name.titleize
I know about the following optimizations already:
- Rendering partials using
:collection - Eager loading with
Post.first(:include => [:tags])
I’m wondering though, if I use Tag.all in my shared/_sidebar.haml template, is there anyway to reuse the result from that query in the post.tags calls?
You can use the
tag_idsmethod on aPostinstance.In your controller create the tag hash. Better still cache the tag hash.
Add this to your
application_controller.rb.Now your partial can be rewritten as
My solution caches the
Tagmodels for 15 minutes. Make sure you add an observer/filter on Tag model to invalidate/update the cache during create/update/delete.In your
config\environment.rbAdd a
tag_observer.rbfile to yourapp\modelsdirectory.Note: Same solution will work with out the cache also.
This solution still requires you to query the
tagstable forTagids. You can further optimize by storing tag ids as a comma separated string in thePostmodel(apart from storing it inpost_tagstable).Now your partial can be rewritten as