Rails模型验证

时间:2013-08-22 18:43:27

标签: ruby-on-rails validation model

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

这就是我原来拥有的:

  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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

如果:allow_nil为真时属性为nil,则只有在存在相关属性的情况下才会运行该特定验证。

答案 2 :(得分:0)

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

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