我在测试项目中使用Nokogiri和mongoid。
这是我的代码:
urls = Array[
'http://www.example.com/cairo',
'http://www.example.com/alexandria',
]
urls.each do |url|
doc = Nokogiri::HTML(open(url))
#Theater and location details here
#movies scrapper starts here
movies = doc.css('.itemContainer')
movies.each do |movie|
#movie title
title = movie.css("h3.catItemTitle a").text
#More code here
#movie synopsis
synopsis = movie.css(".catItemIntroText p").text
Movie.create! {
{title: title}
{synopsis: synopsis }
#{movielength: movielength }
#embedded theater collection
{theaters: {theater: theater,
address: address
}
}
}
end
end
我的mongoid模型看起来像这样:
require 'mongoid'
class Movie
include Mongoid::Document
field :title, :type => String
field :synopsis, :type => String
attr_accessible :title, :synopsis
embeds_many :theaters
end
当我运行Nokogiri脚本时,只保存mongodb objectid并且不会创建或保存字段详细信息。
以下是我的数据库示例:
] }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000011") }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000012") }
{ "_id" : ObjectId("52be9b3c4cfad19f0c000013") }
has more
使用Ruby puts
输出效果很好但是mongodb中的保存很麻烦。我究竟做错了什么?我在Mac OS Mavericks上使用Mongoid(3.1.6)和Ruby 1.9.3p448。
答案 0 :(得分:1)
你正在筑巢哈希。这样做是为了启动:
Movie.create!(title: title, synopsis: synopsis, theaters: [theater])