简体   繁体   English

从同一控制器中的另一个方法调用Ruby on Rails控制器方法会跳过before_filter?

[英]Calling Ruby on Rails controller method from another method in the same controller skips before_filter?

In Ruby on Rails, when I call a controller method from another controller, the before_filter on the targeted method (the one being called) does not execute. 在Ruby on Rails中,当我从另一个控制器调用一个控制器方法时,目标方法(被调用的方法)上的before_filter不会执行。

How can I get this to execute? 我该如何执行?

(Rough example code to follow) (下面的示例代码)

before_filter :filter_method, :only => [:method_b]

def method_a
 if blahblahblah == x
   do_something
     render j
 else
   method_b
 end
end

def method_b
  do_something_else
end

so here filter_method would not execute, how can I change that without rewriting everything? 所以这里filter_method无法执行,如何在不重写所有内容的情况下更改它?

I think you missed how before_filter gets applied in rails. 我认为您错过了before_filter如何在Rails中应用。 It's not applied when you call any method from where ever you want. 当您从任何地方调用任何方法时,都不会应用它。 It applies only when it maps request route to corresponding controller method. 仅在将请求路由映射到相应的控制器方法时适用。 Before filter serves as guard process between request to controller method, not within it. 过滤器充当请求到控制器方法之间的保护过程,而不是在其中。 :) :)

That's correct. 没错 Before actions are only ran when an action is called on the controller, not if you call it yourself. 仅在控制器上调用了某个动作时才运行动作,而不是您自己调用该动作。

The proper way to handle this depends on what your methods do. 处理此问题的正确方法取决于您的方法。 The current way still renders the view from method_b . 当前方式仍通过method_b呈现视图。 Most likely what you want is to redirect to that action but the current way and rendering method_b are both possible as well. 您最可能想要的是重定向到该操作,但是当前方式和渲染method_b也是可能的。

The current way (fixed): 当前方式(固定):

Calls method_b with filter method and renders view from method_a 使用过滤器方法调用method_b并从method_a呈现视图

def method_a
 if blahblahblah == x
   do_something
 else
   filter_method
   method_b unless performed? # In case filter_method renders/redirects
end

Rendering: 渲染:

Calls method_b with filter method and renders view from method_b 使用过滤器方法调用method_b并从method_b呈现视图

def method_a
 if blahblahblah == x
   do_something
 else
   filter_method
   method_b unless performed?
   render :method_b unless performed?
end

Redirecting: 重定向:

Tells the client (browser) to make a new request to method_b . 告诉客户端(浏览器)向method_b发出新请求。 This calls method_b with the filter method and renders view from method_b . 这使用过滤器方法调用method_b ,并从method_b呈现视图。

def method_a
 if blahblahblah == x
   do_something
 else
   redirect_to :method_b
end

Try these ways and see what suits your problem best. 尝试这些方法,看看最适合您的问题的方法。 I cannot make this decision for you since the code example is pretty bare. 由于代码示例非常简单,因此我无法为您做出决定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM