I have several controllers that require a correct user for their edit/update/delete actions. What is the Rails-way to accomplish the following:
Currently, in each controller I have the following code:
class FooController < ApplicationController
before_filter :correct_user, :only => [:edit, :update, :destroy]
# normal controller code
private
def correct_user
@foo = Foo.find params[:id]
redirect_to some_path unless current_user == @foo.user
end
end
I have similar code in 3 controllers. I started to bring it out to a helper like this:
module ApplicationHelper
def correct_user( object, path )
if object.respond_to? :user
redirect_to path unless object.user == current_user
end
end
But I’m wondering if this is a good way to do it. What’s the accepted way to solve this?
Thank you
EDIT
The correct user check here is because I want to make sure it’s only the author who can make edits/deltes to each of the objects.
To clarify, the objects would be things like Questions and Posts. I don’t want to use something like CanCan as it’s overkill for something simple like this.
I really like using RyanB’s CanCan, which allows you to both restrict access to actions based on the user, and centralize such authorization into basically a single file.
EDIT
No problem. I hear you on CanCan – it takes a little while to get up and running on it, but it’s designed to do exactly what you’re asking – per object authorization.
Alternative:
Another way to do this is move your authoriship/current_user check to the
ApplicationControllerclass, from which all of your other Controllers inherit (so they will get that code through inheritance – and you don’t need to write the same code in multiple Controllers), and it would look something like…