Ray*_*d R 5 ruby-on-rails callback controllers
登录后,我让我的SessionsController运行after_action来重置某些用户列.在另一个控制器中,我想在创建和更新时执行相同的after_action.
将相同的代码复制并粘贴到两个控制器中都很容易,但我知道有一天我会在一个控制器中进行更改而忘记更新另一个控制器.
有没有办法从不同的控制器调用与after_action相同的方法?
有几种方法可以做你想要的:
after_action回调调用此方法after_action回调中调用其方法执行:
class ApplicationController < ActionController::Base
# ...
def clean_user_columns
raise 'No user connected!' unless current_user.present?
do_some_stuff
end
Run Code Online (Sandbox Code Playgroud)
用法:
class SessionsController < ApplicationController
after_action :clean_user_columns
Run Code Online (Sandbox Code Playgroud)
执行:
# file created here: /lib/clean_user_columns_after_action.rb
# you will need to restart your server to see the changes of this file
module CleanUserColumnsAfterAction
def clean_user_columns
do_some_stuff
end
end
Run Code Online (Sandbox Code Playgroud)
用法:
class SessionController < ApplicationController
include CleanUserColumnsAfterAction
after_action :clean_user_columns
Run Code Online (Sandbox Code Playgroud)
结论:在我看来,选项#2是要走的路:
include CleanCleanUserColumnsAfterAction行.lib/controllers/来包含每个共享片段您的控制器的代码(如果是这样,请不要忘记将模块重命名Controllers::CleanUserColumnsAfterAction为模块定义+ include语句).| 归档时间: |
|
| 查看次数: |
5829 次 |
| 最近记录: |