如果你走的话here你会看到设备registrations_controller。
它有 build_resource 方法,您在 session_controller 中调用该方法
# Build a devise resource passing in the session. Useful to move
# temporary session data to the newly created user.
def build_resource(hash=nil)
self.resource = resource_class.new_with_session(hash || {}, session)
end
问题是它是受保护的(在 protected 行下),这意味着 build_resource 方法只能从设备registrations_controller 中调用。
它与浏览器配合使用的原因是sessions_controller 中的创建操作调用
super
这意味着它从设计sessions_controller调用创建操作,您的sessions_controller继承自 -
#devise/sessions_controller
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_flashing_format?
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
end
This gist展示如何通过 json api 登录用户。
它使用这个包括
include Devise::Controllers::InternalHelpers
在sessions_controller中。我认为这使得可以使用build_resource
method.
祝你好运!
Edit
def create
respond_to do |format|
# when you log into the application through a web browser you go to the format.html option
# Thus you're not calling the build_resource method
format.html {
super
}
# So, lets try to sign in without the build_resource
# I am not really sure what you can do, but try this
format.json {
resource = User.find_for_database_authentication(:login=>params[:user_login][:login])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user_login][:password])
sign_in("user", resource)
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :login=>resource.login, :email=>resource.email}
return
end
invalid_login_attempt
end
# build_resource # <-This line is evidently producing an error!
# user = User.find_for_database_authentication(:email => params[:user][:email])
# return invalid_login_attempt unless resource
# return invalid_login_attempt unless user