Created
December 21, 2010 22:54
-
-
Save kunzmann/750756 to your computer and use it in GitHub Desktop.
Refactoring
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
class Foo | |
include Mongoid::Document | |
field :bar, :type => Array | |
end | |
# ruby-1.9.2-p0 > Foo.create(:bars => [1,2,3]) | |
# => #<Foo _id: 4d1128c4fddc0d2146000001, bars: [1, 2, 3]> | |
# ruby-1.9.2-p0 > Foo.first.bars | |
# => [1, 2, 3] | |
# After some refactoring... | |
class Foo | |
include Mongoid::Document | |
embeds_many :bars | |
end | |
class Bar | |
include Mongoid::Document | |
field :value, :type => Integer | |
embedded_in :foo, :inverse_of => :bars | |
end | |
# ruby-1.9.2-p0 > Foo.first.bars | |
# NoMethodError: undefined method `klass' for 1:Fixnum | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations/embeds_many.rb:232:in `block in build_children_from_attributes' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations/embeds_many.rb:231:in `each' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations/embeds_many.rb:231:in `each_with_index' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations/embeds_many.rb:231:in `build_children_from_attributes' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations/embeds_many.rb:147:in `initialize' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations.rb:285:in `new' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations.rb:285:in `block (2 levels) in associate' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/memoization.rb:11:in `memoized' | |
# from mongoid-2.0.0.beta.20/lib/mongoid/associations.rb:284:in `block in associate' | |
# ... | |
# You can use attributes to migrate existing data. | |
# | |
# ruby-1.9.2-p0 > f = Foo.first | |
# => #<Foo _id: 4d1128c4fddc0d2146000001, > | |
# ruby-1.9.2-p0 > f.attributes['bars'] | |
# => [1, 2, 3] | |
# ruby-1.9.2-p0 > f.bars = f.attributes['bars'].map {|bar| Bar.new(:value => bar)} | |
# => [#<Bar _id: 4d113271fddc0d222a000005, value: 1>, #<Bar _id: 4d113271fddc0d222a000006, value: 2>, #<Bar _id: 4d113271fddc0d222a000007, value: 3>] | |
# ruby-1.9.2-p0 > f.save | |
# => true | |
# ruby-1.9.2-p0 > f.bars | |
# => [#<Bar _id: 4d113271fddc0d222a000005, value: 1>, #<Bar _id: 4d113271fddc0d222a000006, value: 2>, #<Bar _id: 4d113271fddc0d222a000007, value: 3>] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment