27
loading...
This website collects cookies to deliver better user experience
CSV.parse(csv_text, headers: true).map do |row|
book = Book.find_by(isbn: row["ISBN"])
book.update(publication_date: row["Pub Date"])
end
NoMethodError: undefined method `update' for nil:NilClass
find_by
returns nil
, and calling update
on nil
is exactly our problem. An exception is raised, and further rows of the CSV aren't parsed.update
.CSV.parse(csv_text, headers: true).map do |row|
book = Book.find_by(isbn: row["ISBN"])
if book.blank?
Rails.logger.error("Could not find book")
next
end
book.update(publication_date: row["Pub Date"])
end
CSV.parse(csv_text, headers: true).map do |row|
if row["Pub Date"].blank?
Rails.logger.error("Skipped updating book with no publication date")
next
end
book = Book.find_by(isbn: row["ISBN"])
if book.blank?
Rails.logger.error("Could not find book")
next
end
book.update(publication_date: row["Pub Date"])
end
class BookPublicationDateImportRow
attr_reader :isbn,
:publication_date
def initialize(isbn:, publication_date:)
@isbn = isbn
@publication_date = publication_date
end
def book
@book ||= Book.find_by(isbn: isbn)
end
end
class BookPublicationDateImportRow
include ActiveModel::Validations
validates :book, presence: true
validates :publication_date, presence: true
...
end
save
method that makes sure our instance is passing its own validations before updating the book:class BookPublicationDateImportRow
...
def save
return false unless valid?
book.update(publication_date: @publication_date)
end
end
CSV.parse(csv_text, headers: true).map do |row|
book_import = BookPublicationDateImportRow.new(
isbn: row["ISBN"],
publication_date: row["Pub Date"],
)
if !book_import.save
Rails.logger.error(book_import.errors.full_messages.join(", "))
end
end
This post originally published on The Gnar Company blog.