2016-01-29 105 views
2

我想導入一個csv文件,有美國格式,即MonthDayYear生日和紀念日。我在SO上找到了這個答案,但它對我沒有用。如果我離開關轉換語言,將數據導入爲YearDayMonth,這是不正確的(也跳過日期在一個月> 12下面的代碼:導入csv到Rails的日期錯誤

class Member < ActiveRecord::Base 
    #this is for importing members from csv file 
    def self.assign_from_row(row) 
    member = Member.where(member_id: row[:member_id]).first_or_initialize 
    member.assign_attributes row.to_hash.slice(
     :member_id, :last_name, :first_name, :email, 
     :anniversary => DateTime.strptime(row[4], "%m/$d/%Y").strftime("%Y/%m/%d"), 
     :birthday => DateTime.strptime(row[5], "%m/$d/%Y").strftime("%Y/%m/%d") 
    ) 
    member 
    end 
    end 

的錯誤是「引發ArgumentError在/會員/進口「

同樣,代碼工作儘可能進口,如果我刪除

=> DateTime.strip ... /%d") 

但日期是錯誤的。感謝您的幫助。

回答

1

slice不工作,你有它的方式,你不能提供一個哈希和價值,並期望它在合併這些,你想要更多的東西是這樣的:

member.assign_attributes row.to_hash.slice(
    :member_id, 
    :last_name, 
    :first_name, 
    :email 
).merge(
    :anniversary => DateTime.strptime(row[4], "%m/$d/%Y").strftime("%Y/%m/%d"), 
    :birthday => DateTime.strptime(row[5], "%m/$d/%Y").strftime("%Y/%m/%d") 
) 

雖然,我不能說是否row[4]row[5]是正確的元素,在其他地方使用符號索引到該結構中,但這裏的本質是使用slice(...).merge(...)而不是您擁有的元素。

+1

謝謝。你是對的,排是[[生日]]等行。我因爲一個愚蠢的錯字而苦苦掙扎了很長時間! (:/%米/%d /%Y「) –