Best way to combine fragment and object caching for memcached and Rails

前端 未结 5 717
故里飘歌
故里飘歌 2021-01-31 12:11

Lets say you have a fragment of the page which displays the most recent posts, and you expire it in 30 minutes. I\'m using Rails here.

<% cache(\"recent_posts         


        
5条回答
  •  眼角桃花
    2021-01-31 12:52

    What happens if the cache expires between the time you check for it in the controller and the time it's beeing checked in the view rendering?

    I'd make a new method in the model:

      class Post
        def self.recent(count)
          find(:all, :limit=> count, :order=>"updated_at DESC")
        end
      end
    

    then use that in the view:

    <% cache("recent_posts", :expires_in => 30.minutes) do %>
      <% Post.recent(20).each do |post| %>
         ...
      <% end %>
    <% end %>
    

    For clarity, you could also consider moving the rendering of a recent post into its own partial:

    <% cache("recent_posts", :expires_in => 30.minutes) do %>
      <%= render :partial => "recent_post", :collection => Post.recent(20) %>
    <% end %>
    

提交回复
热议问题