daniel
daniel

Reputation: 9835

DRY me: Rails code

How can I dry this ?

def correct_user
  @company = RealEstateCompany.find(params[:id])     
  if(current_user != @company.user)
    redirect_to(root_path)
  end
end  

def correct_user
 @company = ConstructionCompany.find(params[:id])     
 if(current_user != @company.user)
   redirect_to(root_path)
 end
end

The answer is below and it's as followed in a module:

def correct_user_for_controller?(controller_name)
  @company = controller_name.classify.constantize.find(params[:id])     
  redirect_to(root_path) unless (current_user == @company.user)
end     

Then inside any controller include the model and use

correct_user_for_controller?("ConstructionCompany") 

correct_user_for_controller?("RealEstateCompany")

Upvotes: 1

Views: 221

Answers (3)

mkirk
mkirk

Reputation: 4040

It looks like you are trying to do an authorization check (</clippy>).

Have you checked out any of the existing comprehensive authorization solutions? It might make sense to leverage the effort of others in solving this common problem.

This thread on authorization for rails gives some examples. In particular, with CanCan you could include something like this in the method you are trying to protect:

authorize! :read, @company

Which says "does the current user have permission to see the details of @company".

Upvotes: 2

glebm
glebm

Reputation: 21090

module OwnershipPermission
    def accessible_for_user?(user)
        self.user == user
    end
end

Simply include this module in both models and perform the model level check. You could also create a module for the controller, but I highly advise against that (hurts maintainability).

Upvotes: 3

Harish Shetty
Harish Shetty

Reputation: 64363

Assuming you have want this facility inside ConstructionCompaniesController and RealEstateCompaniesController:

def correct_user
  @company = controller_name.classify.constantize.find(params[:id])     
  redirect_to(root_path) unless (current_user == @company.user)
end 

Upvotes: 1

Related Questions