【问题标题】:How to cache JSON in ruby on rails?如何在 ruby​​ on rails 中缓存 JSON?
【发布时间】:2011-08-28 20:41:14
【问题描述】:

我对如何在我的 rails (2.3.5) 应用程序中使用 json 感到困惑。这些是我需要的元素:

  1. html 模板
  2. json 数据
  3. javascript在模板中渲染数据(我用PURE

使用辅助方法(rails 和我自己的方法)计算的 json 数据非常大,并且不会经常更改(通常是页脚、页眉和页面的其他一些部分),因此应该缓存它。正确的做法是什么?

我尝试了 3 种方法。

一个。

 - html template and javascript to render data placed in the view html.erb
 - method to get json data placed in the helper
    <script type="text/javascript">
      var data= <%= helper_method %>;
    </script>

问题:如何缓存json数据?

B.

 - html template and javascript to render data placed in the view html.erb
 - method to get json data is a controller action
     def footer
        expires_in(4.hours)
        render :json => { calculated_data }
     end
 - ajax request in javascript
      $.ajax({
        type: "GET",
        url: "<%=footer_path %>",
        success: function(data){
          render json data in html template
        }
      });

问题:第二个请求发送到服务器...

C.

 - html template and javascript to render data placed in the view html.erb
 - method to get json data is a controller action
     def footer
        expires_in(4.hours)
        render :json => { calculated_data }
     end
 - data in javascript
    <script type="text/javascript" src="<%=footer_path %>">
    </script>

问题:如何将该脚本的结果传递给我可以在 javascript 中使用的变量,该变量在模板中呈现数据?

在 B 和 C 的情况下,需要在控制器中包含帮助程序(用于计算 json 数据的方法),这是一个非常丑陋的解决方案。

这应该是什么正确的解决方案?哪种方法适合这种需求?

感谢所有建议。

【问题讨论】:

    标签: javascript ruby-on-rails json caching


    【解决方案1】:

    没有回应,但我找到了解决方案。对于那些可能有类似问题的人,也许它会为某人节省时间......

    我使用了方法 A 和 Rails 缓存。我在助手中有一个方法

    def footer
      return Rails.cache.fetch('footer', :expires_in => 4.hours){
        caluclate_data_with_other_methods.to_json
      }
    end
    

    就这个……

    【讨论】:

    • 感谢您抽出宝贵时间回来发布解决方案,您是互联网的英雄:p
    猜你喜欢
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多