git*_*itb 2 ruby-on-rails ruby-on-rails-4
class ParentController < ApplicationController
before_action admin_user, only: [:create, :update]
end
class ChildController < ParentController
before_action admin_user #Also want to add :tweet
def tweet
end
end
Run Code Online (Sandbox Code Playgroud)
在ChildController中,我们可以使用
before_action admin_user, only: [:create, :update, :tweet]
Run Code Online (Sandbox Code Playgroud)
但是,如果我更改了父母的before_action中的任何内容,它将不会在孩子中得到更新。
不幸的是,ActiveSupport::Callbacks实现的方式不允许将附加操作轻松添加到 before 过滤器的配置中。你可以这样做:
class ParentController < ApplicationController
AdminActions = [:create, :update]
before_action :admin_user, only: AdminActions
end
class ChildController < ParentController
before_action :admin_user, only: superclass::AdminActions + [:tweet]
end
Run Code Online (Sandbox Code Playgroud)
您可以在ChildController中的块内调用该方法,而不用按名称传递该方法。看起来像这样:
class ParentController < ApplicationController
before_action admin_user, only: [:create, :update]
end
class ChildController < ParentController
before_action(only: [:tweet]) { admin_user }
def tweet
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
933 次 |
| 最近记录: |