有没有办法阻止before_action在特定路线上运行?比如说,发布执行 api 操作的路由?我的操作目前是这样做的
before_action :setContext
def setContext
@site = Site.find_by!(host: request.subdomain)
@page = Page.find_by!(site_id: @site.id, slug: request.path)
end
Run Code Online (Sandbox Code Playgroud)
在 api 路由上,页面发现 404
您可以使用only和except选项:
before_action :setContext, only: [:show, :edit]
before_action :setContext, except: [:new, :destroy]
Run Code Online (Sandbox Code Playgroud)
您还可以将if:orunless:选项与 lambda 一起使用:
before_action :setContext, if: -> { request.format.html? }
before_action :setContext, unless: -> { request.format.json? }
Run Code Online (Sandbox Code Playgroud)
如果在父类中定义了,您还可以使用skip_before_actionwhich,这很有用:before_action
class ApplicationController
before_action :authenticate_user!
end
class ThingsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index, :show]
end
Run Code Online (Sandbox Code Playgroud)