0

我有一个模型并添加了一些验证

这是我最初拥有的:

  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
4

3 回答 3

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
于 2013-08-22T18:46:29.390 回答
0

验证接受一个:allow_nil参数,如 Rails 指南中所述: http: //edgeguides.rubyonrails.org/active_record_validations.html#allow-nil

如果该属性在:allow_nil为真时为 nil,则该特定验证将仅在相关属性存在时运行。

于 2013-08-22T18:58:08.570 回答
0

我认为,验证数值接受allow_nil属性。尝试这个:

validates :speed, numericality: { only_integer: true, greater_than: 0 }, allow_nil: true
于 2013-08-22T18:58:31.263 回答