滑轨.开发模式下的预加载类 [英] Rails. Preloading class in Development mode

查看:80
本文介绍了滑轨.开发模式下的预加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发模式下预加载Rails模型的正确方法是什么?

What is a right way to preload Rails model in development mode?

背景:Rails 2.2,作为缓存存储区.

Background: Rails 2.2, memcahe as cache store.

Rails首先以生产模式启动时,它会预加载并缓存所有模型. 在开发模式下,它使用延迟加载.这就是为什么我们尝试在应用程序的下一个loadind上将任何模型存储到Rails缓存中的原因,例如,Rails.cache.write("key",User.find(0)) )内存缓存启动,该用户是未知的类/模块.在这种情况下预加载课程的正确方法是什么?

When Rails start in production mode first of all it preload and cache all models. In development mode it use laizy loading. That's why wen we store any model into rails cache, for example, Rails.cache.write("key", User.find(0)) on next loadind of app, when we try do Rails.cache.read("key") memcache fire, that User is unknown class/module. What is a right way to preload class in this situation?

推荐答案

您可以通过执行以下操作来解决此问题:

You can get around this by doing something like this:

User if Rails.env == 'development'
@user = Rails.cache.fetch("key"){ User.find(0) }

这将强制在缓存语句之前重新加载User模型.如果您的类具有多个缓存语句,则可以执行以下操作:

This will force the User model to be re-loaded before the cache statement. If you have a class with multiple cache statements you can do this:

class SomeController
  [User, Profile, Project, Blog, Post] if Rails.env == 'development'

  def show
    @user = Rails.cache.fetch("user/#{params[:user_id]") do
      User.find(params[:user_id])
    end
  end
end

如果您使用的是Rails 2.x,并且Rails.env无法正常工作,则可以始终使用RAILS_ENV或ENV ['RAILS_ENV']代替.当然,您的另一选择是仅在开发环境中禁用缓存,那么您根本不必处理此问题.

If you are in Rails 2.x and Rails.env does not work you can always use RAILS_ENV or ENV['RAILS_ENV'] instead. Of course, your other option is to simply disable caching in your development environment, then you don't have to deal with this issue at all.

这篇关于滑轨.开发模式下的预加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆