簡體   English   中英

Rails模型驗證

[英]Rails Model Validations

我有一個模型,並添加了一些驗證

這是我最初擁有的:

  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

我認為csv的speed值被解釋為字符串。 您可以將.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

驗證接受:allow_nil參數,如Rails指南中所述: http :allow_nil

如果:allow_nil為true時,如果屬性為nil,則只有存在相關屬性時,才會運行特定的驗證。

我認為,驗證數字是否接受allow_nil屬性。 嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM