【问题标题】:How do I pass back an object from a method in Rails 3?如何从 Rails 3 中的方法传回对象?
【发布时间】:2011-04-03 18:56:30
【问题描述】:

我的 Omniauth 回调中有以下内容:

@user = User.find_for_linked_in_oauth(env["omniauth.auth"], current_user)

我希望任何一种方式都能获得用户对象。她是用户方法。现在,我正在测试它无法找到现有用户的情况,因为它尚未创建:

   def self.find_for_linked_in_oauth(omniauth_hash, signed_in_resource=nil)
     debugger
     #omniauth_hash is a hash passed in from env["omniauth_hash"] by callback controller
     linkedin_uid = omniauth_hash['uid']
       debugger
       if user = User.find_by_linkedin_uid(linkedin_uid)
          debugger 
          user
       else # Create an user with a stub password.
         #redirect to a page to ask for an email address and display information
         #User.create!(:email => "token@email.com", :linkedin_uid => linkedin_uid, :password     => Devise.friendly_token[0,20]) 
         user = User.new
         user.first_name = omniauth_hash['user_info']['first_name']
         user.last_name = omniauth_hash['user_info']['last_name']
         user.linkedin_uid = linkedin_uid

         user
         debugger
      end

目前,使用调试器,我返回 '1' 作为 p @user 的值。

我希望将新创建的用户对象传回,这样我就可以要求当前用户在保存之前添加其他信息。

为什么我没有将新创建的用户作为@user 的值?

【问题讨论】:

  • 调试器变量/方法有什么用?这就是 ruby​​ 在 else 块中返回的内容,无论调试器的值是什么。将user 放在下面而不是上面,它将返回用户。
  • @scragz -- 我认为你是对的 -- 现在我收到一个 multi_json 错误,所以无法测试它......有什么想法吗? :)

标签: ruby-on-rails ruby callback debugging models


【解决方案1】:

尝试更改位置 user 和 debugger 以便返回 user

 19   def self.find_for_linked_in_oauth(omniauth_hash, signed_in_resource=nil)
 20     debugger
 21     #omniauth_hash is a hash passed in from env["omniauth_hash"] by callback controller
 22     linkedin_uid = omniauth_hash['uid']
 23       debugger
 24       if user = User.find_by_linkedin_uid(linkedin_uid)
 25          debugger 
 26          user
 27       else # Create an user with a stub password.
 28         #redirect to a page to ask for an email address and display information
 29         #User.create!(:email => "token@email.com", :linkedin_uid => linkedin_uid, :password     => Devise.friendly_token[0,20]) 
 30         user = User.new
 31         user.first_name = omniauth_hash['user_info']['first_name']
 32         user.last_name = omniauth_hash['user_info']['last_name']
 33         user.linkedin_uid = linkedin_uid
 34 
 36         debugger
 35         user
 37      end

【讨论】:

  • @floor,你说得对,这是有道理的......虽然我无法测试它 - 我收到关于“multi_json”的错误 - 不得不发布一个等待帮助甚至让这个工作...... :(有什么建议吗?)
【解决方案2】:

可能是调试器语句搞砸了。尝试交换语句,例如:

debugger
user

在你的函数结束时。

【讨论】:

  • 我正在使用调试器退出,所以我可以看到值是什么......我还能这样做吗?
  • 不,你需要返回你想要的值。如果您需要检查它,最好在您的视图中使用
  • @spoyros,谢谢——我无法测试你的建议,我收到一个关于 multi_json 的新的、不相关的错误?
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2016-09-02
相关资源
最近更新 更多