Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 是否可以跨多个操作使用变量值_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby 是否可以跨多个操作使用变量值

Ruby 是否可以跨多个操作使用变量值,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,我有如下索引和显示方法 def index @variable = SomeModel.includes(:some_other_model) end def show @variable = SomeModel.includes(:some_other_model).find_by!(id: params[:id]) end 所以SomeModel.includes(:some\u other\u model)在这两个动作中都很常见,我在index和show方法中两次在某个其他模型

我有如下索引和显示方法

def index
  @variable = SomeModel.includes(:some_other_model)
end

def show
  @variable = SomeModel.includes(:some_other_model).find_by!(id: params[:id])
end
所以
SomeModel.includes(:some\u other\u model)
在这两个动作中都很常见,我在index和show方法中两次在某个其他模型上进行连接

所以我想让我们在行动之前把它转移到一个私有方法

  before_action :set_something, only: [:index, :update]

    def index
      @variable
    end

    def show
      @variable.find_by!(id: params[:id])
    end

      private

    def set_something
    @variable = SomeModel.includes(:some_other_model) if @variable.nil?
  rescue ArgumentError => e
    render_error(:bad_request, e.message)
  end
所以我的问题是,当调用index或show时,我有没有办法存储@variable值?下次调用其他操作时,只需使用相同的@variable值,不要再次访问数据库

当调用index或show时,以及下次调用其他操作时,是否有任何方法可以存储
@variable
值,只要使用相同的
@variable
值,并且不要再次点击数据库

不,不可能。当调用另一个操作时,它是控制器类的一个完全不同的实例。上次的那个实例变量早就不存在了

除此之外,你应该按照塞巴斯蒂安的建议去做。它是您开始操作的逻辑延续(这样,至少不会在同一操作中两次命中DB)


我们也不能使用类实例变量来实现这一点

使用类级数据,这更容易实现,但前提是只有一个web进程(这样所有请求都保证使用同一个类)。一旦您添加另一个web worker,它将停止工作

这个问题让我再次审视了你的代码,我意识到这一切都是毫无意义的/误导的。:)

这行代码没有命中数据库。因此,试图将其记忆起来是没有意义的。什么也省不了。这就是访问数据库的内容

  @variable = SomeModel.includes(:some_other_model).find_by!(id: params[:id])
                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^

谢谢奇怪的是,我们不能用类实例变量来实现这一点,太好了。谢谢你的帮助。
  @variable = SomeModel.includes(:some_other_model).find_by!(id: params[:id])
                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^