使用.each创建新的Datamapper资源(数据库条目)

时间:2013-05-06 12:23:22

标签: ruby sinatra datamapper ruby-datamapper httparty

我想使用Google自定义搜索API结果并使用Datamapper将它们添加到数据库中。

我已成功设置并手动将一些项目添加到数据库中,因此看起来所有项目都已正确设置。

我正在使用HTTParty将调用作为Google API,即返回JSON结果。然后,我想要使用该JSON并将每个链接添加到数据库中。我正在尝试使用.each,如下所示;

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

Response是一个包含HTTParty :: response的变量,“items”和“link”都是HTTParty :: response的子集。

puts i成功放入了正确的DataMapper资源(即<#DMapperModel city: 'London', link: 'example.com'>

puts i.saved?是检查i是否保存到数据库,此时返回false ...

因此它成功地将i设置为DataMapper资源,但由于某种原因没有将其保存到数据库,有人能看到我出错的地方吗?

1 个答案:

答案 0 :(得分:0)

自己解决了!

我将links参数设置为字符串,DataMapper的默认最大长度为50个字符。我试图添加的所有链接都超过50个字符,因此保存失败。

通过将link参数的最大长度设置为2000个字符来解决问题;

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

我在DataMapper文档中从this page获取了2000个字符的长度,该文档用于URI参数类型并链接到this SO question

一旦我设置了这个,上面的.each方法起了作用。