문제

Is it possible to use Ruby on Rails' before_filter method to check that one of multiple things is true? Specifically, I am using Devise in which I have defined a user and an admin and I would like to ensure that whoever is accessing a specific controller is one or the other. I have looked for answers in documentation and SO and haven't had any luck.

Thanks, here are my versions (if it helps):

  • Ruby 1.9.3
  • Rails 3.2.6
  • Devise 2.2.3
도움이 되었습니까?

해결책

It is possible. I'm hesitant to actually place this as an answer because it doesn't get any simpler than this. I am assuming that you have an admin? method that returns true or false depending on the user's role.

before_filter :check_if_admin

protected

def check_if_admin
  if signed_in?
    raise 'Only admins allowed!' unless current_user.admin?
  else
    # or you can use the authenticate_user! devise provides to only allow signed_in users
    raise 'Please sign in!'
  end
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top