简体   繁体   English

Rails 3.1创建记录而不是更新?

[英]Rails 3.1 create record rather than update?

I have the following Nokogiri rake task in my Rails (3.1) application: 我的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

The time value is the first row in the table and is unique per call (as we can only receive one call at a time). 时间值是表格中的第一行,并且每个呼叫都是唯一的(因为我们一次只能接收一个呼叫)。

What I would like to do is use the time value as the unique identifier for my call logs. 我想做的是将时间值用作呼叫记录的唯一标识符。

So when scraping the screen, it will "update" the existing calls (which won't change but it's the only way I can think of only importing new calls). 因此,在抓取屏幕时,它将“更新”现有的呼叫(不会改变,但这是我可以想到的仅导入新呼叫的唯一方法)。

If I set it to: 如果我将其设置为:

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

and then: 接着:

call.update_attribute(:time, time)

Then it will update the existing records, but I want it to import records that aren't already in our database - based on the time value. 然后它将更新现有记录,但是我希望它基于时间值导入数据库中尚未存在的记录。

Any help is appreciated! 任何帮助表示赞赏!

Do you mean this? 你是这个意思吗

# 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