Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.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 on rails 在rails中使用before_过滤器设置变量_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 在rails中使用before_过滤器设置变量

Ruby on rails 在rails中使用before_过滤器设置变量,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我有一个类FogsController,它有一个过滤器和两个函数 class FogsController < ApplicationController before_filter :check_id, only: [:get_orders] def get_orders #doing some condition with variable **@name** end def call_orders #calling get_orders here

我有一个类FogsController,它有一个过滤器和两个函数

class FogsController < ApplicationController
  before_filter :check_id, only: [:get_orders]

  def get_orders
    #doing some condition with variable **@name**
  end

  def call_orders
    #calling get_orders here
  end

  protected

  def check_id
   @name = params[:name]
   #checking some condition with that **@name**
  end

end
class FogsController

所以我想做的是,我需要调用call\u orders中的get\u orders函数。因此,这里的问题是在函数check\u id触发和设置变量之前,对函数get\u orders的正常调用。那么,当我从call\u orders方法调用get\u orders时,before\u filter函数是如何工作的呢?

在控制器初始化后调用过滤器。因此,如果从另一个操作调用任何操作,则不会执行筛选器


因此,在这种情况下,
check\u id
将只调用一次。

过滤器仅根据发送到控制器的操作进行工作。内部有一个名为
process\u action
的方法,该方法(除其他外)执行该操作的回调。以及行动本身。但是,如果从其他操作调用操作,则不会触发任何回调


通常我建议您不要这样做-重构代码,以便
get_orders
call_orders
调用一个私有方法来完成这项常见的工作(包括设置@name)。

那么在调用函数之前设置所有这些变量的更好方法是什么?这是一个rails内部流程。我会添加一个备选方案,实际上我也尝试过同样的方法,但是当我从call_order调用get_orders时,参数有了新的值,所以我需要传递新的参数,在这个调用中我遇到了问题