我正在将HTML解析为数组,如下所示。我可以将数据放入数组中,然后将数据推送到数据库中。数组数据的一行是:
{:address=>"6222 Lodgepole Dr", :members=>["Diana L Dillard", "Kemberly J Williams", "George S Williams Iii"]}
数据库结果是:
Master Neighbor Name
7545 XYZ Dr --- - 8283 Southern Watch Pl --- - - Diana L Dillard - Kemberly J Williams - George S Williams Iii
这是我的问题:
Address.create
循环仅将数组中的第一个成员(在此示例中为Diana L Dillard
)插入“name”字段而不是所有名称?理想情况下,我想为第一个创建一个字段,然后为所有其他字段创建另一个字段。这是我目前的代码:
url = "XYZ"
doc = Nokogiri::HTML(open(url))
results = []
# parse .single tags
doc.css('.single').each do |single_div|
res = {}
res[:address] = single_div.at_css('span.address').text
res[:members] = single_div.css('li.basic_info').collect{|el| el.text.strip}
results << res
end
results.each do|address|
puts "#{address}: #{members}"
Address.create(:neighboradd => "#{address}", :master => '7545 XYZ Dr', :name => "{members}")
end
答案 0 :(得分:0)
此
results.each do |address|
puts "#{address}: #{members}"
Address.create(
:neighboradd => "#{address}",
:master => '7545 XYZ Dr',
:name => "{members}"
)
end
应该像
results.each do |res|
puts "#{res[:address]}: #{res[:members]}"
Address.create(
:neighboradd => res[:address],
:master => '7545 XYZ Dr',
:name => res[:members].join(', ') # this should be "#{res[members]}"? (with "#")
)
end
---
是因为您使用:neighboradd
的整个哈希值。
如果您只想要第一个成员:
:name => res[:members].first