【问题标题】:Rabl caching with nested objectRabl缓存与嵌套对象
【发布时间】:2013-02-23 00:04:12
【问题描述】:

以下是我的观点:

学生/show.json.rabl

object @student
cache @student
attribute :name, :gender, :age

node :school do |student|
  partial("shared/school", :object => student.school)
end

shared/_school.json.rabl

object @school
cache @school

attributes :id, :name

student.rb:

class Student < ActiveRecord::Base

  belongs_to :school, :touch => true

end

school.rb

class School < ActiveRecord::Base

  has_many :students

end

因此,当我更新学生时,缓存会按预期失效。问题是当我更新学校时,学生没有得到更新的学校属性。当我更新学校模型时,我原以为部分中的缓存 @school 会失效,但事实并非如此。

编辑:添加了对学生的触摸以在更新时使学校无效。

【问题讨论】:

    标签: ruby-on-rails caching ruby-on-rails-3.1 rabl


    【解决方案1】:

    为了帮助别人,这是我现在正在做的事情:

    我将学生展示视图拆分为:

    学生/show.json.rabl:

    extends "students/min_show"
    
    node :school do |student|
      partial("shared/school", :object => student.school)
    end
    

    和学生/min_show.json

    object @student
    cache @student
    attribute :name, :gender, :age
    

    这样我仍然会读取学生的缓存,但学校总是从模板中呈现并单独缓存。

    【讨论】:

      【解决方案2】:

      当Student 更新时,您需要使School 缓存自动过期:

      班级学生<:base>

      belongs_to :school, :touch => true
      

      结束

      【讨论】:

      • 如果学生更新,这绝对有效。但是当学校更新时,它不起作用。基本上,我正在寻找一种方法来进行 2 次缓存读取,一次用于学生,一次用于每个学校。
      【解决方案3】:

      我对您的问题发表了评论,建议在学校下嵌套学生。一个适合您的简单解决方法是:

      cache [@student, @student.school]
      

      这样它会检查两个对象上的 cache_key。

      【讨论】:

        猜你喜欢
        • 2019-08-08
        • 2023-03-18
        • 2020-05-02
        • 2021-06-10
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        相关资源
        最近更新 更多