【发布时间】:2023-04-02 00:35:02
【问题描述】:
在我的Car 模型的JSON 表示中,我包含了一个昂贵方法的输出:
#car.rb
def as_json(options={})
super(options.merge(methods: [:some_expensive_method]))
end
我有一个标准的索引操作:
#cars_controller.rb
respond_to :json
def index
respond_with(Car.all)
end
我还在其他地方使用JSON 表示汽车,如下所示:
#user_feed.rb
def feed_contents
Horse.all + Car.all
end
#user_feeds_controller.rb
respond_to :json
def index
respond_with(UserFeed.feed_contents)
end
因为car 的JSON 表示在多个地方使用,我希望它自己被缓存,使用car.cache_key 作为自动过期的缓存键。
这就是我目前的做法:
#car.rb
def as_json(options={})
Rails.cache.fetch("#{cache_key}/as_json") do
super(options.merge(methods: [:some_expensive_method]))
end
end
将缓存代码放入as_json 是不正确的,因为缓存不是as_json 责任的一部分。这样做的正确方法是什么?我正在使用 Rails 3.2.15。
【问题讨论】:
标签: ruby-on-rails json caching