簡體   English   中英

Rails 3.1創建記錄而不是更新?

[英]Rails 3.1 create record rather than update?

我的Rails(3.1)應用程序中有以下Nokogiri rake任務:

desc "Import incoming calls"
task :fetch_incomingcalls => :environment do

    # Logs into manage.dial9.co.uk and retrieved list of incoming calls.
    require 'rubygems'
    require 'mechanize'
    require 'logger'

    # Create a new mechanize object
    agent = Mechanize.new

    # Load the dial9 website
    page = agent.get("https://manage.dial9.co.uk/login")

    # Select the first form
    form = agent.page.forms.first
    form.username = 'username
    form.password = 'password'

    # Submit the form
    page = form.submit form.buttons.first

    # Click on link called Call Logs
    page = agent.page.link_with(:text => "Call Logs").click

    # Click on link called Incoming Calls
    page = agent.page.link_with(:text => "Incoming Calls").click

    # Output results to file
    # output = File.open("output.html", "w") { |file|  file << page.search("tbody td").text.strip }

    # Add each row to a new call record
    page = agent.page.search("table tbody tr").each do |row|
      next if (!row.at('td'))
      time, source, destination, duration = row.search('td').map{ |td| td.text.strip }
      Call.create!(:time => time, :source => source, :destination => destination, :duration => duration)
    end
end

時間值是表格中的第一行,並且每個呼叫都是唯一的(因為我們一次只能接收一個呼叫)。

我想做的是將時間值用作呼叫記錄的唯一標識符。

因此,在抓取屏幕時,它將“更新”現有的呼叫(不會改變,但這是我可以想到的僅導入新呼叫的唯一方法)。

如果我將其設置為:

Call.find_all_by_time(nil).each do |call|

接着:

call.update_attribute(:time, time)

然后它將更新現有記錄,但是我希望它基於時間值導入數據庫中尚未存在的記錄。

任何幫助表示贊賞!

你是這個意思嗎

# Add each row to a new call record
page = agent.page.search("table tbody tr").each do |row|
  next if (!row.at('td'))
  time, source, destination, duration = row.search('td').map{ |td| td.text.strip }
  call = Call.find_or_create_by_time(time)
  call.update_attributes({:time => time, :source => source, :destination => destination, :duration => duration})
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM