开发者

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开发者_StackOverflow.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")


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).


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".


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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜