2013-08-22 134 views
0

我有一個模型,並增加了一些驗證Rails的模型驗證

這是我本來有:

validates :speed, 
    allow_blank: true, 
    numericality: { only_integer: true, greater_than: 0 } 

,但我一直從我的CSV文件,說明導入項目時得到的錯誤,

速度必須是整數

然後我改變了它到:

validates :speed, 
    numericality: { only_integer: true, greater_than: 0 }, unless: "speed.nil?" 

但我也在這裏得到相同的錯誤。

基本上我希望它能驗證速度是數字的,並且大於1,除非沒有速度傳入並允許空白值。

任何想法?

CSV進口商:

def self.import_from_csv(file) 
    Coaster.destroy_all 

    csv_file = CSV.parse(
     File.read(
     file.tempfile, 
     {encoding: 'UTF-8'} 
    ), 
     headers: true, 
     header_converters: :symbol 
    ) 

    csv_file.each do |row| 

     coaster_name = row[:name] 

     # No need to keep track of coasters already in the database as the CSV only lists each coaster once unlike parks 

     # create the new coaster 
     park = Park.find_by_name_and_location_1(row[:park], row[:location_1]) 
     manufacturer = Manufacturer.find_by_name(row[:manufacturer]) 

     coaster = Coaster.create!({ 
     name:    row[:name], 
     height:   row[:height], 
     speed:   row[:speed], 
     length:   row[:length], 
     inversions:  row[:inversions] == nil ? 0 : row[:inversions], 
     material:   (row[:material].downcase if row[:material]), 
     lat:    row[:coaster_lat], 
     lng:    row[:coaster_lng], 
     park_id:   park.id, 
     notes:   row[:notes], 
     powered:   row[:powered], 
     manufacturer_id: (manufacturer.id if manufacturer), 
     covering:   row[:covering], 
     ride_style:  row[:ride_style], 
     model:   row[:model], 
     layout:   row[:layout], 
     dates_ridden:  row[:dates_ridden], 
     times_ridden:  row[:times_ridden], 
     order:   row[:order], 
     on_ride_photo: row[:on_ride_photo] == 1 ? true : false, 
     powered:   row[:powered] == 1 ? true : false 
     }) 

     ap "Created #{row[:name]} at #{row[:park]}" 

    end 
    end 

回答

1

我認爲從CSV速度值被解釋爲字符串。您可以使用.to_i與您用於速度的特定值。改變你的代碼是這樣的:

park = Park.find_by_name_and_location_1(row[:park], row[:location_1]) 
    manufacturer = Manufacturer.find_by_name(row[:manufacturer]) 
    row_speed = row[:speed].blank? ? nil : row[:speed].to_i 

    coaster = Coaster.create!({ 
    ..... 
    speed:   row_speed, 
    ..... 
    }) 

然後在驗證:

validates :speed, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true 
+0

你可以粘貼你的代碼,你用來導入CSV到數據庫。 –

+0

已在原始文章中添加。我檢查了CSV,其中的項目沒有引號,所以我不明白爲什麼它會認爲它們是字符串? – rctneil

+0

我將使用哪個驗證,第一個示例或第二個示例?如果值存在,我想驗證數字行,否則只允許空白。 – rctneil

0

我認爲,驗證數值接受allow_nil屬性。試試這個:

validates :speed, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true