I have a .txt file full of attributes like so:

"12345", "1", "Kent"
"67890", "1", "New Castle"

I need this to update my County model, and so I have this rake task:

namespace :data do
  desc "import data from files to database"
  task :import => :environment do
    file = File.open(File.join(Rails.root, "lib", "tasks", "counties.txt"), "r")
    file.each do |line|
      attrs = line.split(", ")
      c = County.find_or_initialize_by_number(attrs[0])
      c.state_id = attrs[1]
      c.name = attrs[2]
      c.save!
    end
  end
end

All seems to be well, but when I check in the console to make sure it was imported correctly, I get this:

#<County id: 2, name: nil, number: 0, state_id: 0, created_at: "2013-08-04 17:44:11", updated_at: "2013-08-04 17:44:11"> 

I know that it's actually importing something, because it has created exactly the right number of County records, but it's not actually updating the attributes correctly. I'm sure I'm missing something very obvious but I can't find it!

有帮助吗?

解决方案

Assumption: County.number is defined as an integer field.

attrs[0] after your line.split comes out to be "\"12345\"" (a string). The find_by method defaults the lookup key to 0 (integer) given that it's looking up an integer field (number). This would explain why your code works when you manually strip out the quotation marks from the first data column in the text file.

Based on this root cause, there could be multiple ways to resolve your issue. Here's an ugly way:

c = County.find_or_initialize_by_number(Integer(attrs[0].gsub(/\"/, '')))

Ideally, I would trim out (or gsub) quotes when doing the line text split.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top