You're getting the undefined method []
error when you try to use the []
method on a class that doesn't have that method defined. My guess is that you are running into this problem while parsing the above hash (e.g. calling []
on Nil Class, and getting the error undefined method [] for nil:NilClass
).
Long Story Short: You need to parse the JSON and save the items you need to the appropriate spots in the database
I'm a little unclear about the example you gave, so I'll try to use a simplified one.
Suppose you are querying for a TvShow
, which belongs_to
a TvChannel
. TvChannel
also has_many_and_belongs_to
a certain Category
. So perhaps this query you are doing returns the TvShow
, along with the TvChannel
and Category
to which the TvShow
belongs. Suppose you get back something like the json below:
json_response = { 'name': 'Desperate Housewives',
'id': '12345-67890',
'tvChannel': {
'name': 'ABC',
'id': '123-456-789',
'categories': [
{ 'name': 'Comedy',
'id': '000-000' },
{ 'name': 'Drama',
'id': '111-111' }
]
}
}
So now you want to save the TvShow
Desperate Housewives to the TvChannel
ABC, and save ABC to the Categories
Comedy and Drama. This is how I would go about parsing:
new_show = TvShow.new
new_show.name = json_response["name"]
new_show.external_id = json_response["id"] # assuming you want to save their identifier
channel = TvChannel.find_or_create_by(:name, json_response["tvChannel"]["name"]) # you might want to do this by the id, but it's up to you.
new_show.tv_channel = channel # this saves the TvChannel's ID to the new_show's tv_channel_id foreign key field
new_show.save # save your new TV Show to the database, with the name, id, and tv_channel_id.
# Next we parse the "categories" part of the JSON, finding each Category by name (creating a new Category if one doesn't exist by that name),
# And then adding our TvChannel to that Category
json_response["tvChannel"]["categories"].each do |category|
c = Category.find_or_create_by(:name, category["name'])
channel.categories << c
channel.save
end
I hoped this helped show you how to parse JSON responses, and how to use ActiveRecord to create or find instances in your database. It is useful to store the JSON response to a variable (json_response
in my example above), for easier parsing.
Let me know if I can clarify anything!