Rails - 用于nil的未定义方法`api_key':NilClass

时间:2013-08-08 21:30:48

标签: ruby-on-rails ruby ruby-on-rails-3

我试图将我的api密钥存储在yaml文件中

fresh_desk.yml

production:
  :api_key: 12345

staging:
  :api_key: 12345

development:
  :api_key: my api key here

然后在我的lib文件夹中,我有一个名为

的文件

fresh_desk_api_wrapper.rb

  class FreshDeskApiWrapper

  attr_accessor :config, :client

  def initialize
self.config = YAML.load("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new("http://onehouse.freshdesk.com/", config.api_key, "X")
  end

  def post_tickets(params)
client.post_tickets(params)
  end
end

然后在我的

clients_controller.rb

def create
  FreshDeskApiWrapper.new().post_tickets(params[:client])
  redirect_to new_client_path
end

但是当我提交表单时出现错误

undefined method `api_key' for nil:NilClass

有谁知道造成这种情况的原因是什么?以及如何解决它?

1 个答案:

答案 0 :(得分:1)

你可能需要一个File.open
blah.yml

production:
  :api_key: 12345

staging:
  :api_key: 45678

development:
  :api_key: 10203

然后您可以将其加载到哈希

>> require 'yaml'
=> true
>> config = YAML::load(File.open('blah.yml'))
=> {"production"=>{:api_key=>12345}, "staging"=>{:api_key=>45678}, "development"=>{:api_key=>10203}}