How can I send a parameter to a before filter?

后端 未结 5 1983
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 10:55

I\'d like to create a before_filter method in my application controller like this...

def check_role(role_name)
  unless logged_in_user.has_role? role_name
    fl         


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-08 11:21

    I don't believe you can pass parameters to filters. So what I have do in the past is made static methods that pass the parameter to the method that needs the params.

    So I would have something like this:

    def check_role(role_name)
      unless logged_in_user.has_role? role_name
        flash[:notice] = 'Access to that area requires additional privileges.'
        redirect_to :back
      end
    end
    
    def check_admin_role
       check_role('admin')
    end
    
    def check_blah_role
       check_role('blah')
    end
    

    Then in your controller you'd just call

    before_filter :check_admin_role
    

    There is probably some way to implement this with meta-programming but I am still quite a n00b and haven't figured that part out yet ;)

提交回复
热议问题