【发布时间】:2018-01-23 08:17:46
【问题描述】:
我的 ApplicationController 中有以下 before_actions:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
before_action :logged_in_user
before_action :admin_user
private
# Confirms a logged-in user.
def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
我的 PostsController 中有 skip_before_actions:
class PostsController < ApplicationController
skip_before_action :logged_in_user, except: [:new, :edit, :update, :destroy]
skip_before_action :admin_user, except: [:new, :edit, :update, :destroy]
before_action :find_post, only: [:edit, :update, :show, :delete]
find_post 操作完美运行,并且该方法在该控制器中。我希望能够在不登录或成为管理员的情况下访问posts#index 和posts#show,但我尝试的一切都不会跳过这些操作,并且我被重定向到登录。它在我的其他控制器中工作.我通过路由到static_pages#home 并在static_pages 控制器中使用skip_before_action 将该操作定义为render posts/index 来解决索引问题。在之前的尝试中,我尝试不将 before 操作放入 ApplicationController,而仅在需要时在 PostsController 和 UsersController 中调用 before_action,但 PostsController 也没有这样做。我在PostsController 中写了一个测试操作,只是redirect_to 并尝试在所有内容上调用before_action :test_action,它也不会这样做。我错过了什么?
【问题讨论】:
-
你能把它放到 Github 的某个地方吗?听起来你做的一切都是正确的,你可能错过了一些东西。轶事:我认为使用 skip_before_action 省略您为应用程序中的所有控制器设置的回调是一种代码味道。我会亲自从
ApplicationController中删除这些回调,并在需要时调用回调。从长远来看,您可能会伤害自己。 -
我已经在 bitbucket 上找到了...我现在只是想学习。我知道,跳过操作很混乱,但我迫切希望找到解决方案...git@bitbucket.org:kylealm/rails-sample-app.git
-
你需要把它公开(我确定这是 Bitbucket 里面的东西),或者跳到 Github
-
好了,现在应该好点了吧?
-
是的!你能确保你的代码也是最新的吗?我没有看到您在 posts_controller.rb 中所做的更改 :)
标签: ruby-on-rails