Staffan Jonsson
Staffan Jonsson

Reputation: 45

Best way to restrict actions (edit/delete) with Ruby on Rails and Devise

I am fairly new to Ruby On Rails and right now I am doing a simple app. In this app a user can create many items and I use devise for authentication. Ofcourse I want to make sure that you are the owner in order to delete items (Teams, Players etc) and the way I do it now is:

def destroy
    @team = Team.find(params[:id])
    if current_user.id == @team.user_id 
      @team.destroy    
      redirect_to(teams_url, :notice => 'The team was deleted.')
    else
      redirect_to root_path
    end      
end

Is this the best way? I was thinking about putting a method in the model but I am not sure I can access current_user from there. I was also thinking about a before_filer, something like:

before_filter :check_ownership, :only => [:destroy, :update]

I that case and if I want to code only one method for all objects (all objects this relates to have a "user_id"-field)

Upvotes: 2

Views: 582

Answers (2)

brad
brad

Reputation: 32345

You're looking for an authorization solution on top of your authentication (devise)

You can't access current user in the model no. I've had a fair amount of success using Makandra's Aegis for authorization. It allows you to create roles specify permissions attributed to each role. The docs are pretty good and I know it works fine with Devise, it's pretty agnostic that way, I've also used it with Clearance. It also passes an implicit "current_user" to your permissions so you can specify and check that your current user can take appropriate actions.

Upvotes: 0

drummondj
drummondj

Reputation: 1483

In my application controller I put:

before_filter :authorize

def authorize
  false # Or use code here to check if user is admin or not
end

Then I override the authorize method in my actual controller to allow access to various actions.

Upvotes: 1

Related Questions