我知道这样做的唯一方法是使用 2 个作用域。这是一个示例,其中我两次声明了相同的范围,但其中一个使用了额外的:auth 管道。请注意我如何使用:only 选项来指定允许哪些控制器方法:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :auth do
plug MyAppWeb.Auth
end
scope "/", MyAppWeb do
pipe_through :browser
resources "/posts", PostController, only: [:index]
end
scope "/", MyAppWeb do
pipe_through :browser
pipe_through :auth
resources "/posts", PostController, only: [:show, :new, :create]
end
诀窍是使用:only 来说明允许以这种方式调用控制器中的哪些函数。路由器将匹配它找到的第一个,所以如果你在两个范围内使用相同的方法两次,比如:index,那么它将使用第一个范围(即第一个词法定义的范围。-第一个在文件)。
我希望这是有道理的。如果你愿意,我可以解释更多。
附:也许可以尝试一下,看看它是否有效:
scope "/", MyAppWeb do
pipe_through :browser
resources "/posts", PostController, only: [:index]
pipe_through :auth
resources "/posts", PostController, only: [:show, :new, :create]
end