bmargulies
bmargulies

Reputation: 100186

'date must not be blank' but it isn't blank (ActiveRecord validation)

Here's a Ruby function in a rails app in the class that corresponds to my table:

 def self.import(file)
    line = 1
    CSV.foreach(file.path, headers: true) do |row|
      reading_hash = row.to_hash
      logger.debug("line #{line}")
      logger.debug(reading_hash)
      Reading.create!(reading_hash)
      line = line + 1
    end # end CSV.foreach
  end

I see this value in the debugger:

reading_hash = Hash (5 elements)
 'date' => 9/19/2015
 'name' => Vayeilech
 'reading' => Hosea 14:2-10; Micah 7:18-20; Joel 2:15-27 | Shabbat Shuva
 'assigned_to' => Spencer Ross (20th bar mitzvah anniversary) Gene Achter (deferred, please find another day for him)
 'comments' => Shabbat Shuvah

I also print the hash to the logger:

  {"date"=>"9/19/2015", "name"=>"Vayeilech", "reading"=>"Hosea 14:2-10; Micah 7:18-20; Joel 2:15-27 | Shabbat Shuva", "assigned_to"=>"Spencer Ross (20th bar mitzvah anniversary) Gene Achter (deferred, please find another day for him)", "comments"=>"Shabbat Shuvah"}

But if I continue into create!, I'll get:

Validation failed: Date can't be blank

This happens on the third record, the first two work fine.

Perhaps I should also cite the validation:

  validates :date, presence: true

Upvotes: 0

Views: 168

Answers (2)

madcow
madcow

Reputation: 2633

Can you format your csv dates to one of the below formats? That will make it work. Any of these formats will insert the date you want:

2015/09/19 2015/9/19 19/09/2015

Upvotes: 1

stephenmurdoch
stephenmurdoch

Reputation: 34643

Put quotes around the date. I think that will fix it.

Upvotes: 0

Related Questions