Last active
September 29, 2016 13:37
-
-
Save nicolasblanco/a28ccacb53e6ca80e8a32f13ec21b89b to your computer and use it in GitHub Desktop.
Mongoid : migrate an existing String field to a localized field
This file contains hidden or 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
| # 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 |
This file contains hidden or 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
| # 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When going from a classical
Stringfield in Mongoid to a localized field (withlocalize: trueoption), it can be painful to migrate the existing records.This is a small add-on to
mongoid_rails_migrationsI use to easily migrate the records.