This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the user-input-and-output category.
Last Updated: 2024-11-21
The following code caused a failure in production:
def tag_list=(names)
self.tags = names.split(',').map do |n|
Tag.where(name: n.strip).first_or_create!
end
end
The problem was that someone input the following as tags in the form
"instruments, "
(i.e. a trailing comma), and the code tried to create a blank
tag.
The fix:
def tag_list=(names)
self.tags = names.split(',').map do |n|
next if n.blank?
Tag.where(name: n.strip).first_or_create!
end
end
When splitting on delimiter (e.g. comma), anticipate a blank or nil entry.