![](/img/trans.png)
[英]How to create a new record or update if a particular record based on an attribute other than record id exists, Ruby on Rails?
[英]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.