mercredi 26 octobre 2016

Accessing first element of array in rails

I am getting below json from backend.

{ drug:
  {

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

I dont want direction as array. I want it as object so I wrote method drug_format to parse json

My ruby on rails code for parsing is as follows :

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

Now when I am trying to run my code I am getting following error.

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'

What can be the issue?

Aucun commentaire:

Enregistrer un commentaire