forked from collectiveidea/clear_empty_attributes
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rename rake task to db:clear_empty_attributes and refactor to use all…
… tables by default
- Loading branch information
Showing
1 changed file
with
10 additions
and
11 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,16 @@ | ||
namespace :clear_empty_attributes do | ||
desc "clear all blank strings of the given MODELS" | ||
task :clear_all_blank_strings do | ||
raise "rake clear_empty_attributes:clear_all_blank_strings MODELS=User,Movie,... to clear blank strings of those models" unless ENV['MODELS'] | ||
models = ENV['MODELS'].split(',').map(&:constantize) | ||
|
||
models.each do |model| | ||
puts "#{model}:" | ||
model.columns.select(&:text?).each do |column| | ||
namespace :db do | ||
desc "Clear all blank strings in the database. Specify TABLES=table1,table2 to limit to specific tables." | ||
task :clear_empty_attributes => :environment do | ||
connection = ActiveRecord::Base.connection | ||
tables = ENV['TABLES'] ? ENV['TABLES'].split(/,/) : connection.tables | ||
tables.each do |table| | ||
puts "#{table}:" | ||
connection.columns(table).select(&:text?).each do |column| | ||
name = column.name | ||
puts " #{name}" | ||
model.update_all("#{name} = NULL","#{name} = ''") | ||
column_name = connection.quote_column_name(column.name) | ||
connection.update("UPDATE #{connection.quote_table_name(table)} SET #{column_name} = NULL WHERE #{column_name} = ''") | ||
end | ||
puts '' | ||
end | ||
end | ||
end |