class ApplicationController < ActionController::Base
before_action :test, only: [:index]
def test
ap 'test'
end
end
以上是在每一个索引动作之前运行的,无论是狗#index还是猫#index还是兔子#index。我应该如何让它在cat#index和rabbits #index?
之前执行我希望测试在许多控制器中的操作之前进行测试。
答案 0 :(得分:7)
您可以跳过此方法:
class ApplicationController < ActionController::Base
before_action :test, only: [:index]
def test
p 'test'
end
end
class DogsController < ApplicationController
skip_before_action :test
end
答案 1 :(得分:4)
只需将您的呼叫转移到您希望其运行的控制器中。
class ApplicationController < ActionController::Base
# nothing here!
def test
# ...
end
end
class CatsController < ApplicationController
before_action :test, only: [:index]
end
class RabbitsController < ApplicationController
before_action :test, only: [:index]
end
答案 2 :(得分:0)
其实很简单
在 application_controller 中创建 before_action 并检查 if:
传入的请求是针对相关的_controller。
class ApplicationController < ActionController::Base
before_create :assign_setting, only: :create, if: :registration_controller?
def registration_controller?
params["controller"] == "registrations"
end
def assign_settings
# your code
puts "settings applied"
end
end