Home > Software engineering >  NoMethodError: Unable to access the field over an array of hashes from an HTTP response
NoMethodError: Unable to access the field over an array of hashes from an HTTP response

Time:08-07

I spend a time to find a solution how to convert an array came from the HTTP request to something can rails read.

Example of the request:

 "line_item":[{
     "item_id": 1,
     "item_name": "Burger",
     "item_price": 15.00,
     "item_quantity": 2
 },
 {
     "item_id": 2,
     "item_name": "Soda",
     "item_price": 3.00,
     "item_quantity": 1
 }]

and then I loop the array like so:

    @not_available_items = []
    @line_item = @order.line_item
    
    @line_item.each do |i| 
      @item = Item.find(i.item_id)
      if @item.is_active == false
        @not_available_items.push(
          {
            item_id: i.item_id,
            item_name: i.item_name
          }
        )
      end
    end

The error message:

"exception": "#<NoMethodError: undefined method `item_id' for {\"item_id\"=> 1, \"item_name\"=>\"Burger\", \"item_price\"=> 15.0, \"item_quantity\"=> 2}:Hash>"

Hope I explained the issue clear.

Thanks

CodePudding user response:

The variable i is an object of type Hash (and not of type Item). In Ruby, unlike Javascript, you cannot access the key of a Hash object using the . operator.

You can use the [] operator to fetch the value for a key in a Hash.

In your code, you are using i.item_id, but i does not have an attribute or method called item_id; it has a key item_id. Since, i is a Hash, you can access the fields by calling and i["item_id"]

    @not_available_items = []
    @line_item = @order.line_item
    
    @line_item.each do |i| 
      @item = Item.find(i["item_id"])
      if @item.is_active == false
        @not_available_items.push(
          {
            item_id: i.item_id,
            item_name: i.item_name
          }
        )
      end
    end
  • Related