Question

I want to take Google Custom Search API results and add them to a database using Datamapper.

I've managed to successfully set up and manually add some items to the database, so it seems like that is all set up correctly.

I'm using HTTParty to make the call the the Google API, which is returning JSON results. I then want to take that JSON and add each link into the database. I'mtrying to use .each as follows;

response["items"].each do |item|
    i=DMapperModel.create(city: "London", link: item["link"])
    puts i
    puts i.saved?
end

Response is a variable holding the HTTParty::response, "items" and "link" are both subsets of the HTTParty::response.

puts i successfully puts the correct DataMapper resource (i.e. <#DMapperModel city: 'London', link: 'example.com'>)

puts i.saved? is a check to see if i saved to the database, at the moment this is returning false...

So it is successfully setting i to the DataMapper resource, but not saving it to the database for some reason, can anyone see where I'm going wrong?

Was it helpful?

Solution

Solved it myself!

I had the links parameter set as a string, which DataMapper sets at a default maximum length of 50 characters. All of the links I was trying to add were longer that 50 characters so the save was failing.

Resolved the problem by setting the maximum length of the link parameter to 2000 characters;

class CityLink
    include DataMapper::Resource
    property :id, Serial
    property :city, String
    property :link, String, *length: 2000*
end

I took the length of 2000 characters from this page on the DataMapper docs which is for the URI parameter type and links to this SO question.

Once I'd set this, the above .each method worked a trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top