在过滤器为整个控制器分配异常之前

时间:2013-03-23 17:55:52

标签: ruby-on-rails ruby-on-rails-3 devise ruby-on-rails-3.2 before-filter

我的Users中的每一个与has_many都有Character关系。现在,在他们可以使用应用程序之前,我需要他们首先选择一个角色作为他们的主要因此我想继续将它们重定向到members控制器显示方法,直到他们选择主角。

我的方法可行,但是当有人例如想要在选择主角色之前注销时会出现问题,它会将它们重定向到member_path。如何将devise控制器添加到此规则的异常和我的整个members控制器。

class ApplicationController < ActionController::Base
  protect_from_forgery

    before_filter :check_for_main
    skip_before_filter :check_for_main, :only => [:members => :show, :users => :sign_out]

    # Check if user has a main character selected
    private
    def check_for_main

        # Check signed in user
        if user_signed_in?

            # Check associated characters if any are set as main
            redirect_to member_path(current_user.id), :alert => "Please select your main character."
            unless current_user.characters.any?(&:main)

            end
        end
    end

end

2 个答案:

答案 0 :(得分:1)

在您的MembersControllerUsersController中,您应该skip_before_filter :check_for_main使用:only选项,指定应跳过过滤器的控制器中的哪些操作。你目前有

skip_before_filter :check_for_main, :only => [:members => :show, :users => :sign_out]

但那应该是

# in MembersController
skip_before_filter :check_for_main, :only => [:show]

# in UsersController
skip_before_filter :check_for_main, :only => [:sign_out]    

答案 1 :(得分:1)

我不希望通过添加另一个控制器来为我的代码行添加另一个控制器来代替我的代码:skip_before_filter。我的第一次尝试是添加skip_before_filter来设计控制器自己,但你应该真的避免这种情况。

无论如何运行rake routes表明设计控制器实际上名称为devise/controller_name,名称前始终为devise/ prefix。由于我不打算进一步扩展设计控制器,只有有意义的是向方法添加一个条件语句,它自己跳过设计包中的请求。

对于我所有其他控制人员,我遵循@Stuart M建议。

我的新代码:

class ApplicationController < ActionController::Base
    protect_from_forgery

    before_filter :check_for_main

    # Check if user has a main character selected
    private
    def check_for_main

        # Check signed in user
        if user_signed_in?

            if not params[:controller].to_s.include? "devise"
                # Check associated characters if any are set as main
                if not current_user.characters.any?(&:main)
                    redirect_to member_path(current_user.id), :alert => "Please select your main character."
                end
            end
        end
    end

end
相关问题