mahemoff
mahemoff

Reputation: 46389

Devise current_user in routes.rb

Is there any way to access the current user in routes.rb? I would like a mapping like this:

match /profile => redirect("/profiles/{current_user.name}")

env['warden'] doesn't seem to be set up, so I can't access warden.user.name.

Upvotes: 7

Views: 3806

Answers (3)

mb21
mb21

Reputation: 39209

To expand on user1136228's answer:

get '/profile', to: redirect { |params, request|
  me = request.env["warden"].user(:user)
  me ? ('/profiles/' + me.name) : '/'
}

Upvotes: 6

user1136228
user1136228

Reputation: 977

The are two possibilities. If you are using devise you can use warden like so:

current_user = request.env["warden"].user(:user)

or without warden

User.find_by_id(request.session[:user_id])

if you store your user's id in session's :user_id

Upvotes: 3

alf
alf

Reputation: 18530

Not sure that's possible. However, you could use a controller:

def profile
    if signed_in?
        redirect_to user_profile_path(current_user)
    else
        redirect_to root_url
    end
end

Upvotes: 7

Related Questions