0

我似乎在我的Ruby on Rails应用程序中有一个授权呃逆。我一直在我的应用程序控制器中使用以下方法,并且它一直在工作得很漂亮。如何处理由于控制器命名错误导致的授权呃逆?

def require_owner 
    obj = instance_variable_get("@#{controller_name.singularize.camelize.underscore}") # LineItem becomes @line_item 
    return true if current_user_is_owner?(obj) 
    render_error_message("You must be the #{controller_name.singularize.camelize} owner to access this page", root_url) 
    return false 
end 

我然后在特定的控制器过滤:

before_filter :require_owner, :only => [:destroy, :update, :edit] 

我最近创建了有一点,这似乎是导致问题的不同的命名约定的一个新的控制器。通常我的控制器读取messages_controllerposts_controller。在这个特定的情况下,我将资源box_wod命名为box_wods_controller

这是唯一的控制器,似乎有这个过滤器的问题,所以我敢打赌,我可以告诉它是在它的命名,因此application_controller方法不承认记录的所有者。

我没有收到错误消息,但应用程序不让我编辑,更新或销毁记录,因为我不是BoxWod owner。我的路线是正确的,因为我的关联和正确的信息传递到box_wod表。

有没有办法重写application_controller方法来识别box_wod资源中的下划线?或者这甚至是我的问题?

UPDATE:

下面是在BoxWodsController的三种方法:

def edit 
    @workout_count = Workout.count 
    @box_wod = BoxWod.find(params[:id]) 
    end 

    def update 
    @box_wod = BoxWod.find(params[:id]) 

    respond_to do |format| 
     if @box_wod.update_attributes(params[:box_wod]) 
     flash[:notice] = 'BoxWod was successfully updated.' 
     format.html { redirect_to(@box_wod) } 
     format.xml { head :ok } 
     else 
     format.html { render :action => "edit" } 
     format.xml { render :xml => @box_wod.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

    def destroy 
    @box_wod = BoxWod.find(params[:id]) 
    @box_wod.destroy 

    respond_to do |format| 
     format.html { redirect_to(box_wods_url) } 
     format.js 
    end 
    end 
+0

我觉得很难让它的控制器文件的命名导致你的问题。您可以将问题控制器的相关部分添加到您的问题中吗? – karmajunkie 2010-12-07 22:27:24

回答

2

在这样的情况下,我喜欢创造,我可以在必要时改写的控制器方法。例如:

# application_controller.rb 
class ApplicationController 
    def require_owner 
    obj = instance_variable_get("@#{resource_instance_variable_name}") 
    # Do your authorization stuff 
    end 

    private 

    def resource_instance_variable_name 
    controller_name.singularize.camelize.underscore 
    end 
end 

# box_wods_controller.rb 
class BoxWodsController 
    private 

    def resource_instance_variable_name 
    'box_wod' # Or whatever your instance variable is called 
    end 
end 

最后,请发表您的BoxWodsController代码,以便我们能更好地诊断问题。

1

看起来@box_wod实例变量不会被创建,直到require_owner方法被调用,因此current_user_is_owner?正在检查一个零值,导致它总是返回false。在调用require_owner之前,可能需要另一个before_filter来填充实例变量。