我有一个模型并添加了一些验证
这是我最初拥有的:
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