dcalixto
dcalixto

Reputation: 411

Rails current_user best practice

I'm on a dilema, a have a ton of objects associated to the current_user on my app. And and don't know if in my controllers i keep using the IDs to find these objects or put directly the current_user + object.

Exemple:

class HousesController < ApplicationController

 def show
      @house = House.find(params[:id]) **or?** @house = current_user.house 
    end

 def edit
      @house = House.find(params[:id]) **or?** @house = current_user.house 
    end
end

And this going on and on. thank's in advance

Upvotes: 2

Views: 2005

Answers (1)

DGM
DGM

Reputation: 26979

If you use House.find(params[:id]) you have a potential security hole, as a given user could simply change the number in the url and access the house for a different user. So if you go this route, you have to add something to protect unathorized access.

OTOH, current_user.house keeps them on their own house, but needs alternate code for admin functions.

For simple applications, you can do this by hand, but for larger applications, you might want to consider authorization frameworks such as cancan or declarative_authorization where you can more easily define the permissions.

I use decl_auth myself, and all my controllers either use its method of loading the resource with filter_resource_access (loads the appropriate resource or throws and error if not allowed) or by hand with House.with_permissions_to(:index) which will only give me a house if I have permission to load it.

As always, Railscasts say it best: cancan and declarative authorization.

Upvotes: 4

Related Questions