Ruby-on-rails 带参数的 before_filter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5507026/
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
before_filter with parameters
提问by choise
I have a method that does something like this:
我有一个方法可以做这样的事情:
before_filter :authenticate_rights, :only => [:show]
def authenticate_rights
project = Project.find(params[:id])
redirect_to signin_path unless project.hidden
end
I also want to use this method in some other Controllers, so i copied the method to a helper that is included in the application_controller.
我也想在其他一些控制器中使用此方法,因此我将该方法复制到 application_controller 中包含的帮助程序。
the problem is, that in some controllers, the id for the project isn't the :idsymbol but f.e. :project_id(and also a :idis present (for another model)
问题是,在某些控制器中,项目的 id 不是:id符号而是 fe :project_id(并且还:id存在 a(对于另一个模型)
How would you solve this problem? is there an option to add a parameter to the before_filter action (to pass the right param)?
你会如何解决这个问题?是否可以选择将参数添加到 before_filter 操作(以传递正确的参数)?
回答by Alex
I'd do it like this:
我会这样做:
before_filter { |c| c.authenticate_rights correct_id_here }
def authenticate_rights(project_id)
project = Project.find(project_id)
redirect_to signin_path unless project.hidden
end
Where correct_id_hereis the relevant id to access a Project.
correct_id_here访问 a 的相关 id在哪里Project?
回答by Vadym Tyemirov
With some syntactic sugar:
加上一些语法糖:
before_filter -> { find_campaign params[:id] }, only: [:show, :edit, :update, :destroy]
Or if you decide to get even more fancy:
或者,如果您决定变得更加花哨:
before_filter ->(param=params[:id]) { find_campaign param }, only: %i|show edit update destroy|
And since Rails 4 before_action, a synonym to before_filter, was introduced, so it can be written as:
由于引入before_action了Rails 4的同义词before_filter,所以它可以写成:
before_action ->(param=params[:id]) { find_campaign param }, only: %i|show edit update destroy|
NB
NB
->stands for lambda, called lambda literal, introduce in Ruby 1.9
->代表lambda,称为lambda 文字,在 Ruby 1.9 中引入
%iwill create an array of symbols
%i将创建一个符号数组
回答by Augustin Riedinger
回答by Subtletree
I find the block method using curly braces instead of do...endto be the clearest option
我发现使用花括号的块方法而不是do...end最清晰的选择
before_action(only: [:show]) { authenticate_rights(id) }
before_actionis just the newer preferred syntax for before_filter
before_action只是较新的首选语法 before_filter
回答by Matheus Moreira
This should work:
这应该有效:
project = Project.find(params[:project_id] || params[:id])
This should return params[:project_id]if it is present in the params hash, or return params[:id]if it isn't.
params[:project_id]如果它存在于 params 哈希中,则应该返回,否则返回params[:id]。

