ruby Rails 4 before_action,将参数传递给调用的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19260288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4 before_action, pass parameters to invoked method
提问by Parsa
I have the following code:
我有以下代码:
class SupportsController < ApplicationController
before_action :set_support, only: [:show, :edit, :update, :destroy]
....
Is it possible to pass a string to the method set_supportto be applied for all 4 view methods?
Is it possible to pass a different string to the method set_supportfor each method in the view?
是否可以将字符串传递set_support给要应用于所有 4 个视图方法的方法?是否可以将不同的字符串传递给set_support视图中每个方法的方法?
回答by Linus Oleander
before_action only: [:show, :edit, :update, :destroy] do
set_support("value")
end
回答by Kyle Decot
You can use a lambda:
您可以使用 lambda:
class SupportsController < ApplicationController
before_action -> { set_support("value") },
only: [:show, :edit, :update, :destroy]
...
回答by cb24
A short and one-liner answer (which I personally prefer for callbacks) is:
一个简短的单行答案(我个人更喜欢回调)是:
before_action except:[:index, :show] { method :param1, :param2 }
Another example:
另一个例子:
after_filter only:[:destroy, :kerplode] { method2_namey_name(p1, p2) }
回答by tihom
You can pass a lambda to the before_actionand pass params[:action]to the set_supportmethod like this:
您可以将 lambdabefore_action传递params[:action]给并传递给set_support方法,如下所示:
class SupportsController < ApplicationController
before_action only: [:show, :edit, :update, :destroy] {|c| c.set_support params[:action]}
....
Then the param being sent is one of the strings: 'show', 'edit', 'update'or 'destroy'.
然后发送的参数是字符串之一:'show', 'edit','update'或'destroy'。
回答by Darlan Dieterich
The SupportsController
支持控制器
class SupportsController < ApplicationController
before_action only: [:show, :edit, :update, :destroy] { |ctrl|
ctrl.set_support("the_value")
}
...
The ApplicationController
应用程序控制器
class ApplicationController < ActionController
def set_support (value = "")
p value
end
...

