问题
I want a before filter like "must_have_permission_to_write" that when called if user hasn't permission to write renders a message saying "you can't do that!" and return.
Problem is I'm getting "can only render or redirect once per action" of course... how can I stop the execution in the before filter? thanks
回答1:
I think the easiest answer is add a redirect and return false to your must_have_permission_to_write
method.
def must_have_permission_to_write
unless current_user.has_permission?(something)
redirect_to access_denied_path
return false
end
end
Then, create an action for access denied somewhere, add the route, and put whatever you want in the template.
回答2:
There are a few things I noticed about the posts here:
- Calling render or redirect in a before filter WILL cancel the action. There was a point when rails did not do this, but as far as I know, this is automatic now. I can't seem to find a reference to this online, someone please correct me if I am wrong.
- Using "and return" is a great way to cancel the action if you are actually inside the action. In the examples above the methods are defined as a before filter (i.e. seperate methods) calling "and return" at the end of a method, is not that useful.
- I don't think you should be telling someone "you can't do that", thats not a very secure practice. If someone asks for something they dont have permission to, the response should be 404. By responding like that you are giving this "curious" person too much information.
回答3:
Just add the and return
, like doing:
before_filter :must_have_permission_to_write
def must_have_permission_to_write
redirect_to login_path and return unless current_user
end
来源:https://stackoverflow.com/questions/1487925/rails-put-and-interruption-in-before-filter