Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1075319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T21:15:21+00:00 2026-05-16T21:15:21+00:00

Not sure how to word the question concisely :). I have say 20 Posts

  • 0

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:

  1. Rendering partials using :collection
  2. 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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T21:15:21+00:00Added an answer on May 16, 2026 at 9:15 pm

    You can use the tag_ids method on a Post instance.

    In your controller create the tag hash. Better still cache the tag hash.

    Add this to your application_controller.rb.

    def all_tags
      @all_tags ||=Rails.cache.fetch('Tag.all', :expire_in => 15.minutes)){ Tag.all }
      # without caching
      #@all_tags ||= Tag.all
    end
    
    
    def all_tags_hash
      @all_tags_hash ||= all_tags.inject({}){|hash, tag| hash[tag.id]=tag;hash}
    end
    
    def all_tags_by_ids ids
      ids ||= []
      ids = ids.split(",").map{|str| str.to_i} if ids.is_a?(string)
      all_tags_hash.values_at(*ids)
    end
    helper_method :all_tags, :all_tags_hash, :all_tags_by_id
    

    Now your partial can be rewritten as

    # posts/_item.html.haml
    - all_tags_by_ids(post.tag_ids).each do |tag|
      %li
        %a{:href => "/tags/#{tag.name}"}= tag.name.titleize
    

    My solution caches the Tag models 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.rb

    config.active_record.observers = :tag_observer
    

    Add a tag_observer.rb file to your app\models directory.

    class TagObserver < ActiveRecord::Observer
    
      def after_save(tag)
        update_tags_cache(tag)
      end
    
      def after_destroy(tag)
        update_tags_cache(tag, false)
      end
    
      def update_tags_cache(tag, update=true)
        tags = Rails.cache.fetch('Tag.all') || []
        tags.delete_if{|t| t.id == tag.id}
        tags << tag if update
        Rails.cache.write('Tag.all', tags, :expire_in => 15.minutes)
      end
    end
    

    Note: Same solution will work with out the cache also.

    This solution still requires you to query the tags table for Tag ids. You can further optimize by storing tag ids as a comma separated string in the Post model(apart from storing it in post_tags table).

    class Post < ActiveRecord::Base
      has_many :post_tags
      has_many :tags, :through => :post_tags
    
      # add a new string column called tag_ids_str to the `posts` table.
    end
    
    class PostTag < ActiveRecord::Base
      belongs_to :post
      belongs_to :tag
      after_save :update_tag_ids_str
      after_destroy :update_tag_ids_str
    
      def update_tag_ids_str    
        post.tag_ids_str = post.tag_ids.join(",")
        post.save
      end
    end
    
    class Tag < ActiveRecord::Base
      has_many :post_tags
      has_many :posts, :through => :post_tags
    end
    

    Now your partial can be rewritten as

    # posts/_item.html.haml
    - all_tags_by_ids(post.tag_ids_str).each do |tag|
      %li
        %a{:href => "/tags/#{tag.name}"}= tag.name.titleize
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Not sure how to word this algorithm question, actually. I have toggle buttons in
Not sure exactly how to word this question ... so edits are welcomed! Anyway
Not sure how to word the question... Basically, so far all my SQL stuff
Not quite sure how to word this question. I am wondering if there is
I'm not sure the best way to word this question so bear with me.
Not really too sure how to word this question, therefore if you don't particularly
Sorry if this has been asked, I am not sure how to best word
Not sure if the title is quite right for the question but I can't
Not sure what's going on here. I have a DateTime object, and when I
Not sure this is a programming question, but we use LaTeX for all our

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.