zer02
zer02

Reputation: 4011

Rails: JSON attribute is handled as a method. No method error

I am having problems accessing the attributes of my JSON data. Instead of accessing the JSON data it thinks it is a function.

 @response = HTTParty.get('http://localhost:4000/test')
 @json = JSON.parse(@response.body)
  @json.each do |pet|
  MyModel.create(pet)       ! WORKS
  puts "my object #{pet}"   ! WORKS
  puts "my object attribute #{pet.myattribute}" ! DOES NOT WORK
  end

With no MethodError myattribute.

Thank you for any help!

Upvotes: 1

Views: 1612

Answers (2)

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 18567

You may be used to JavaScript, where both object.some_key and object["some_key"] do the same thing. In Ruby, a hash is just a hash, so you have to access values via object["some_key"]. A Struct in Ruby is similar to a JavaScript object, in that you can access values both ways, but the keys have to be pre-defined.

Upvotes: 2

house9
house9

Reputation: 20614

@json = JSON.parse(@response.body) returns a hash, so you would need to do

puts "my object attributes #{pet['id']}, #{pet['title']}"

you might want to convert to HashWithIndifferentAccess so you can use symbols instead of quoted strings, i.e.

@json = JSON.parse(@response.body).with_indifferent_access
# ...
puts "my object attributes #{pet[:id]}, #{pet[:title]}"

Upvotes: 1

Related Questions