在rails中访问数组的第一个元素

时间:2016-10-26 10:25:50

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

我从后端到达json。

{ drug:
  {

    "id": "580f323ee4b06ffee69041a1",
    "direction": [
        {
            "direction": "test",
            "discarded": false
        }
    ]
  }
}

我不希望方向为数组。我希望它作为对象,所以我写了方法drug_format来解析json

我的ruby on rails代码用于解析如下:

def drug_format drug
{
  id: drug[:id],
  direction: drug[:direction][0],
}
end

现在,当我尝试运行我的代码时,我遇到了错误。

NoMethodError (undefined method `[]' for nil:NilClass):
    app/controllers/drugs_controller.rb:280:in `drug_format'
    app/controllers/drugs_controller.rb:15:in `block in index'
    app/controllers/drugs_controller.rb:14:in `each'
    app/controllers/drugs_controller.rb:14:in `index'

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

json键是字符串而不是符号,所以你需要像:

def drug_format drug
  {
    id: drug['id'],
    direction: drug['direction'][0]
  }
end

或者您可以使用with_indifferent_access

控制台输出:

params = {
 'drug' => {
    "id" => "580f323ee4b06ffee69041a1",
    "direction" => [
        {
            "direction" => "test",
            "discarded" => false
        }
    ]
  }
}
=> {"drug"=>{"id"=>"580f323ee4b06ffee69041a1", "direction"=>[{"direction"=>"test", "discarded"=>false}]}}

params[:drug]
=> nil

params['drug']
=> {"id"=>"580f323ee4b06ffee69041a1", "direction"=>[{"direction"=>"test", "discarded"=>false}]}

def drug_format(drug)
  {
    id: drug['id'],
    direction: drug['direction'][0]
  }
end
=> :drug_format

drug_format(params[:drug])
=> NoMethodError: undefined method `[]' for nil:NilClass

drug_format(params['drug'])
=> {:id=>"580f323ee4b06ffee69041a1", :direction=>{"direction"=>"test", "discarded"=>false}}