我是 Ruby 生态系统的新手,快被淹死了。我想我被带有 C# 的 Visual Studio 的简单智能感知宠坏了。不管怎样,我在 Ubuntu 上使用 Ruby 1.9.3、Rails 3.2.13 和 Devise 3.0.3。 我可以通过 PC 上的浏览器登录到这个网站。但是当我尝试从我们的 Phonegap 移动应用程序执行此操作时,出现此错误:
NameError: 'undefined local variable or method 'build_resource' for # ..
这是 sessions_controller.rb 中的代码:
class SessionsController < Devise::SessionsController
def create
respond_to do |format|
format.html {
super
}
format.json {
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
..
显然,是包含 build_resource 的行产生了错误。如果能帮我指出去哪里,我将不胜感激。那条线到底有什么作用?那是方法调用吗?如何发现所谓的内容?
最佳答案
如果你去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 (在 protected 行下),这意味着只能从设计注册 Controller 调用 build_resource 方法。
它与浏览器一起工作的原因是 session_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
这gist展示了如何通过 json api 登录用户。
它使用这个包含
include Devise::Controllers::InternalHelpers
在 session Controller 中。我认为这使得使用 build_resource
方法成为可能。
祝你好运!
编辑
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
关于ruby-on-rails - Ruby Devise,SessionsController.create,json - 获取 NameError : undefined 'build_resource' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22758288/