2014-04-02 23 views
0

「我從一個CSV文件導入紀錄,需要添加的問題是我沒有任何標識的文件之前檢查現有的記錄查找帶有多個協會

這裏是車型。:

class Shooter < ActiveRecord::Base 
    has_many :scores 
end 

class Event < ActiveRecord::Base 
    has_many :shooters 
    has_many :scores 
end 

class Score < ActiveRecord::Base 
    belongs_to :shooter 
    belongs_to :event 
end 

這裏是我的導入方法:

def self.import(file) 
    CSV.foreach(file.path, headers: true) do |row| 
     # some_how_find_duplicates_here... 
     score.attributes = row.to_hash 
     score.save! 
    end 
    end 

我猜我需要名稱進行搜索,並做一些事情,如:

score = Score.where("shooter.name == row.shooter_name & event.name == row.event_name") || new 

任何方向將不勝感激。

+0

這是獨特的領域? –

+0

在這個階段,我正在驗證shooter.name和event.name的唯一性 – Kiwi

回答

0

而是創建對象,然後搜索重複然後刪除,你爲什麼不從一開始就過濾CSV的投入,特別是如果它不是一個巨大的文件

由於CSV行是一個數組,我們可以疊加的行在數組中的Array和使用uniq到重複的行過濾掉:

def self.import(file) 
    rows = [] 
    CSV.foreach(file.path, headers: true) do |row| 
    rows << row  
    end 
    # remove out duplicates 
    rows.uniq! 

    #now create objects 
    rows.each do |row| 
    score.attributes = row.to_hash 
    score.save! 
    end 
end 

注:

Uniq接受一個塊來解釋如何唯一性被檢查(例如,通過第一列僅該行的 - 檢查API文檔鏈接以更多細節)從文檔

例如:

c = [["student","sam"], ["student","george"], ["teacher","matz"]] 
c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]] 

更新

由於比較應該與數據庫中的記錄來完成,我們做一個小mofication到上面的代碼:

def self.import(file) 
    rows = [] 
    CSV.foreach(file.path, headers: true) do |row| 
    rows << row  
    end 
    # remove out duplicates 
    rows.reject! {|row| Score.where("shooter_name = ? AND event_name = ?",row[shooter_name_col_no],row[event_name_col_no]).any?} 

    #now create objects 
    rows.each do |row| 
    score.attributes = row.to_hash 
    score.save! 
    end 
end 

這裏我們使用reject!,如果塊參數返回true,它將刪除行。現在,您應該修改正確的屬性名稱和行列號,以使其工作。

+0

對不起,我沒有正確解釋自己。我需要檢查數據庫的現有分數。即射擊者每個事件只能有一個得分。 – Kiwi

+0

@奇異,確定更新了我的答案 – Nimir