Get User ID from Devise, Ruby on Rails
I use Devise and Basic HTTP Authentication to access user areas from a mobile app. When the user enters its details in the app and it tries to "login" (you don't actually login with basic auth as you send the credentials with each request) I want to get a response back with the user info, like user ID and email.
When I try to get a resource I get a response like this:
[
-
{
email: "em...@example.com"
username: "Example"
}
-
[
-
{
created_at: "2011-07-26T11:30:55Z"
id: 1
title: "开发者_开发百科Test"
updated_at: "2011-07-26T11:30:55Z"
user_id: 1
}
-
{
created_at: "2011-07-26T16:53:26Z"
id: 2
title: "Test2"
updated_at: "2011-07-26T16:53:26Z"
user_id: 1
}
]
]
So I get the user object at the beginning. However, I need to add the user ID as well. I can't use the user_id in the items because that won't be rendered if the user has no items.
Any tips?
You probably need to extend Devise::SessionsConroller
. In your controllers folder, add a users folder and then add a file called sessions_controller.rb
that contains this:
class Users::SessionsController < Devise::SessionsController
def new
super
render :json => {:id => current_user.id}.to_json
end
end
In your routes.rb
:
devise_for :users,
:controllers => {:sessions => 'users/sessions'}
EDIT
Try this. Take that line out of your routes.rb
. In application_controller.rb
add this:
# Devise override
def after_sign_in_path_for(resource)
render :json => {:id => resource.id}.to_json
end
after an aftternoon to try to find a good answer, i've found this:
Resource: http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
Hope it Helps!
精彩评论