2012-01-09 1 views
0

私はできるだけ簡単にHTMLテーブルを解析している次のコードを持っています。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 

上記のコードはうまく機能しますが、各項目を新しいレコードとして扱います。だから、時間行のそれぞれのレコード、それはサイクル上記のコードを作るが、1つのレコードに4つの項目を追加し、移動の最も簡単な方法は何ソース列など

の一人一人のために別のレコードを追加しています次のレコードに?すべてのヘルプは高く評価され

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 

:追加情報については

は、ここに私のデータベース構造を示して移行ファイルです。

答えて

1

各列の代わりに各行を反復することを検討してください。

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 
1

毎回call.createを呼び出す代わりに、すべてのソースを文字列に追加し、最後にレコードを保存します。

+0

これを行う方法の例や、おそらくドキュメントへのリンクを教えてください。 – dannymcc

関連する問題