Rails Devise current_user is undefined in a matches? advanced route constraint

后端 未结 3 565
深忆病人
深忆病人 2021-01-05 14:35

I get an error NameError (undefined local variable or method \"current_user\" for #): when I try to use current_user in a

相关标签:
3条回答
  • 2021-01-05 15:06

    Building on ksol's post, you can ensure user.is_test by passing a block to authenticated:

    authenticated :user, lambda {|u| u.is_test } do
        // route stuff here
    end
    

    This is assuming that u.is_test returns a Boolean value.

    0 讨论(0)
  • 2021-01-05 15:08

    current_user is only available in your controllers and views. There is more than one way to achieve what you want, the easier being supplying it as a parameter to your method.

    EDIT

    if current_user if accessible in the router, you can pass it to your constraints class by doing constraints: APIRouter.new(current_user). Then you need to define APIRouter#initialize and store the current_user in an instance var that you can use in matches?.

    EDIT 2

    I just remembered devise allows you to do this in your router :

    authenticated :user do
      root :to => "main#dashboard"
    end
    

    I don't know how to ensure that user.is_test though.

    EDIT 3

    Last attempt. request.env["warden"].user(:user) should give you a user if one is authenticated.

    0 讨论(0)
  • 2021-01-05 15:12

    Just remember to add diff :as for both root otherwise it will through error

    authenticated :user do
      root :to => "main#dashboard", :as => :foo
    end
    
    root :to => "main#landing_page"
    
    0 讨论(0)
提交回复
热议问题