Skip to content

Instantly share code, notes, and snippets.

@nicolasblanco
Last active September 29, 2016 13:37
Show Gist options
  • Select an option

  • Save nicolasblanco/a28ccacb53e6ca80e8a32f13ec21b89b to your computer and use it in GitHub Desktop.

Select an option

Save nicolasblanco/a28ccacb53e6ca80e8a32f13ec21b89b to your computer and use it in GitHub Desktop.
Mongoid : migrate an existing String field to a localized field
# db/migrate/20160929132327_localize_species.rb
class LocalizeSpecies < Mongoid::Migration
def self.up
migrate_field_to_localized(Species, :name)
end
def self.down
end
end
# config/initializers/mongoid_migration.rb
module Mongoid
class Migration
def self.migrate_field_to_localized(klass, field_name)
klass.all.each do |record|
next unless record[field_name].is_a?(String)
old_value = record[field_name]
record.unset(field_name)
record.send("#{field_name}=", old_value)
record.save
end
end
end
end
@nicolasblanco
Copy link
Copy Markdown
Author

nicolasblanco commented Sep 29, 2016

When going from a classical String field in Mongoid to a localized field (with localize: true option), it can be painful to migrate the existing records.

This is a small add-on to mongoid_rails_migrations I use to easily migrate the records.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment