【问题标题】:Mongoid access issueMongoid 访问问题
【发布时间】:2017-03-14 06:26:50
【问题描述】:

我正在编写一个应用程序,里面有一个数据库。我正在使用 MongoId。它只是一个只有一个条目的数据库。我正在这个数据库中保存一个令牌

api.rb

    def get_wink_token
      retrieve_token.present? ? retrieve_token : new_token
    end

    def new_token
      RestClient.get "#{ENV['DOMAIN']}/oauth2/authorize?response_type=code&client_id=#{ENV['CLIENT_ID']}&redirect_uri=#{ENV['REDIRECT_URI']}"
      token_credentials = RestClient.post "#{ENV['DOMAIN']}/oauth2/token", credentials, headers
      access_token = JSON.parse(token_credentials)['data']['access_token']
      TokenDb.any_in(:name => 'Token').destroy_all
      TokenDb.create(name:'Token', token:access_token)
      access_token
    end

    def retrieve_token
      TokenDb.where(:name => 'Token').present? ? TokenDb.where(:name => 'Token').first[:token] : nil
    end

通过new_token 获取令牌的过程运行良好。我的问题是我在执行 TokenDb.where 时发生了崩溃。现在产生崩溃。

TokenDB 类定义如下:

class TokenDb
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic

  field :name,      type:String
  field :token,     type:String

  validates_presence_of :name, :token
end

我要做的是检查数据库tokenDb是否有一个名为 Token 的条目并检索数据,如果没有,我生成一个新密钥

2017-03-13 23:18:08 - NoMethodError - undefined method `each' for nil   /Users/sebastien/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:22:in `present?'
    /Users/sebastien/smarthome/models/credentials.rb:23:in `retrieve_token'

问题发生在 TokenDb.where... 行

有什么想法吗?

【问题讨论】:

  • 您遇到了什么错误?它们是在客户端还是服务器端,还是两者兼而有之?

标签: ruby mongodb mongoid


【解决方案1】:

您可以简单地使用find_by 并在异常不存在时挽救它:

def get_wink_token
  TokenDb.find_by(name: 'token').token
rescue Mongoid::Errors::DocumentNotFound
  create_token
end

def create_token
  RestClient.get "#{ENV['DOMAIN']}/oauth2/authorize?response_type=code&client_id=#{ENV['CLIENT_ID']}&redirect_uri=#{ENV['REDIRECT_URI']}"
  token_credentials = RestClient.post "#{ENV['DOMAIN']}/oauth2/token", credentials, headers
  access_token = JSON.parse(token_credentials)['data']['access_token']
  TokenDb.any_in(:name => 'Token').destroy_all
  TokenDb.create(name: 'Token', token: access_token)
  access_token
end

虽然仅仅为此使用数据库是大材小用...

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2011-06-16
    • 2023-03-25
    相关资源
    最近更新 更多