Cache only the main content in rails

前端 未结 2 830
旧巷少年郎
旧巷少年郎 2021-01-29 01:36

Using Rails 3.1.1 and Heroku.

I believe this should be a fairly easy fix but I cannot find (and easily verify) how to do this. I have a very slow controller (6 sec)

相关标签:
2条回答
  • 2021-01-29 01:53

    Use fragment caching, and don't load things in the controller.

    If you have a very complex query, let it live in the controller as a scope, and only evaluate it in the view.

    If you have a complex process to do so the query must be executed, use a helper method.

    If you manage to just load lazy queries in the controller, if the cache is hit none of them will be executed.

    0 讨论(0)
  • 2021-01-29 01:56

    You can achieve this with fragment caching like below:

    def show
    
      if !fragment_exist?("main_content")
        @products = Product.all
        @users_count = User.count
      end
    
      @random_products = Product.order("RANDOM()").limit(10)
    
    end
    

    show.html.erb

    <!--MAIN CONTENT-->
    <% cache("main_content") do %>
        <%= @users_count %>
        <% @products.each do |product| %>
            <%= product.name %>
        <% end %>
    <% end %>
    
    <!--SIDE CONTENT-->
    <% @random_products.each do %>
        <%= product.name %>  
    <% end %>
    
    0 讨论(0)
提交回复
热议问题