开发者

Rails & Rake task - How to prevent duplicates

开发者 https://www.devze.com 2023-02-11 10:36 出处:网络
How to prevent duplicates in rake task ? I have tried to write something but are totally blank. I want to check if the column Date matches the date today if that is true then just update the column w

How to prevent duplicates in rake task ? I have tried to write something but are totally blank.

I want to check if the column Date matches the date today if that is true then just update the column with the scraped data unless create a new row with the scraped data.

    desc "Importer statistikker"
    namespace :reklamer do
      task :import_stats => :environment do
        require 'Mechanize'
        agent = WWW::Mechanize.new
        agent.get("http://www.iqmedier.dk")

        form = agent.page.forms.first
        form.Username = 'username'
        form.Password = 'password'
        form.submit

        agent.page.link_with(:href => "/Publisher/Stats").click
        form = agent.page.forms.first
开发者_开发知识库        form.submit

        @stats = agent.page.search('//tr')[-2].search('td').map{ |n| n.text }
        if Reklamer.find(:all) where column is = Date.today if turns true 
          then update that row with @stats
        else
          Reklamer.create!(:virksomhed => 'Iqmedier', :dato => @stats[0], :unik_klik => @stats[1], :klik => @stats[2].to_i, :unik_vis => @stats[3], :vis => @stats[4], :leads => @stats[5], :ordre => @stats[6], :cpc => @stats[7], :earn => @stats[8])
        end
      end
    end

Best regards, Rails beginner


Here is what you probably want to do:

existing = Reklamer.find(:first, :conditions => {:column => Date.today})
if existing.nil?
  Reklamer.create! :virksomhed => 'Iqmedier', :dato => @stats[0], ...
else
  existing.update_attributes :virksomhed => 'Iqmedier', :dato => @stats[0], ...
end

This code will check if a Reklamer object already exists with column being equal to Date.today. It will then either update the existing one or create a new one.

0

精彩评论

暂无评论...
验证码 换一张
取 消