Rails 4 before_action,将参数传递给调用的方法

我有以下密码:

class SupportsController < ApplicationController
before_action :set_support, only: [:show, :edit, :update, :destroy]
....

是否有可能将一个字符串传递给方法 set_support,以应用于所有4个视图方法? 是否可以为视图中的每个方法向方法 set_support传递不同的字符串?

47385 次浏览
before_action only: [:show, :edit, :update, :destroy] do
set_support("value")
end

You can pass a lambda to the before_action and pass params[:action] to the set_support method like this:

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'.

You can use a lambda:

class SupportsController < ApplicationController
before_action -> { set_support("value") },
only: [:show, :edit, :update, :destroy]
...

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) }

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
...