Created
June 26, 2023 14:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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