每次都将html解析为Rails而不使用新记录?

每次都将html解析为Rails而不使用新记录?,html,parsing,nokogiri,mechanize,Html,Parsing,Nokogiri,Mechanize,下面的代码尽可能简单地解析HTML表 # Timestamp (Column 1 of the table) page = agent.page.search("tbody td:nth-child(1)").each do |item| Call.create!(:time => item.text.strip) end # Source (Column 2 of the table) page = agent.page.search("tbody td:nth-child(2)"

下面的代码尽可能简单地解析HTML表

# Timestamp (Column 1 of the table)
page = agent.page.search("tbody td:nth-child(1)").each do |item|
  Call.create!(:time => item.text.strip)
end

# Source (Column 2 of the table)
page = agent.page.search("tbody td:nth-child(2)").each do |item|
  Call.create!(:source => item.text.strip)
end

# Destination (Column 3 of the table)
page = agent.page.search("tbody td:nth-child(3)").each do |item|
  Call.create!(:destination => item.text.strip)
end

# Duration (Column 4 of the table)
page = agent.page.search("tbody td:nth-child(4)").each do |item|
  Call.create!(:duration => item.text.strip)
end
尽管上面的代码运行良好,但它将每个“项”视为一个新记录。因此,它为每个时间行添加一条记录,为每个源列添加另一条记录,等等

让它循环上面的代码,但将四个项目添加到一个记录中,然后移动到下一个记录,最简单的方法是什么

有关其他信息,请参阅迁移文件,其中显示了我的数据库结构:

class CreateCalls < ActiveRecord::Migration
  def change
    create_table :calls do |t|
      t.datetime :time
      t.string :source
      t.string :destination
      t.string :duration

      t.timestamps
    end
  end
end
class CreateCalls

感谢您的帮助。

不要调用call。每次创建只需将所有源代码附加到一个字符串,并在末尾保存记录。

考虑在每行而不是每列上迭代

page = agent.page.search("table tbody tr").each do |row|
  time        = row.at("td:nth-child(1)").text.strip
  source      = row.at("td:nth-child(2)").text.strip
  destination = row.at("td:nth-child(3)").text.strip
  duration    = row.at("td:nth-child(4)").text.strip
  Call.create!(:time => time, :source => source, :destination => destination, :duration => duration)
end

你能给我举个例子说明如何做到这一点,或者给我一个指向一些文档的链接吗?