开发者

Authorative deleting (and not only that)

开发者 https://www.devze.com 2023-01-12 07:38 出处:网络
Lets see controller: def destroy if session[:user_id] && User.find(session[:user_id]).is_admin @exam = Exam.find(params[:id])

Lets see controller:

def destroy
    if session[:user_id] && User.find(session[:user_id]).is_admin
          @exam = Exam.find(params[:id])
          @exam.destroy
    else
          redirect_to :back, :notice => "You cant do that!"
          return
    end
      redirect_to 开发者_StackOverflow社区:root
    end 

its in Exams controller But i want analogically have this functionality in let's say User_controller. What is proper way to Dont repeat myself?


There are several things that are repetitve. For the find stuff, I recommend inherited resources and for authorization, it's more complicated. We're using #may_be_deleted_by?(user) (or updated/viewed) per model and hook the check inside build/create/delete/update_resource of IR.


The general way to do this is add a method to your application_controller.rb that checks for a user session (probably pass in the user) and if the user is found from the session, checks if that user is_admin per your code.

Then from each of your other controllers, since they extend from ApplicationController, add a before_filter :check_for_admin, :only => :destroy (or whatever your method is called) on any of the actions you care about. You could repeat the before_filter... line at the top of all controllers where you'd want to use this. The authorization logic is extracted to its own method. We have used a setup like this with AuthLogic on several projects, you can google for specific code examples, but again, the general pattern is to extract common controller code to the app controller and call it with a before_filter.

0

精彩评论

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