Skip to content

Instantly share code, notes, and snippets.

@Joeventures
Created June 26, 2023 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joeventures/b25616f8be215570a0c81fd67c443685 to your computer and use it in GitHub Desktop.
Save Joeventures/b25616f8be215570a0c81fd67c443685 to your computer and use it in GitHub Desktop.
Find all fields that have data with leading or trailing spaces in Rails
# Given several models with string or text fields
# where data entered those fields often contain
# leading or trailing spaces, find those fields.
Rails.application.eager_load!
problematic = {}
ApplicationRecord.descendants.each do |model|
model_key = model.to_s.downcase.to_sym
problematic.merge!({ model_key => [] })
model.attribute_names.each do |attribute|
problem = model.where("LEFT(#{attribute}, 1) = ' ' OR RIGHT(#{attribute}, 1) = ' '").any?
problematic[model_key] << attribute if problem
end rescue next
end
problematic.reject! { |k,v| v.empty? }
# Result:
# {
# model: ["field_1", "field_2"]
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment