How to merge records in Mongoid

36 views
Skip to first unread message

Arthur Petrov

unread,
Sep 17, 2014, 6:32:52 PM9/17/14
to rubyonra...@googlegroups.com
I would like to ask how can merge data with Mongoid, when I inserting
new data

class Record
include Mongoid::Document
include Mongoid::Attributes::Dynamic
field :header1, :type => String
field :header2, :type => String
validates :header1, uniqueness:{scope: :header2}
end
Then I want to create a database from arrays of hashes

record1 = [{"header4" =>"value4"}, {"header3" =>"value3"},
{"header5"=>"value5"}, {"header1"=>"value1"}, {"header2"=>"value2"}]
record2 = [{"header4" =>"value4"}, {"header3" =>"value3"},
{"header5"=>"value5"}, {"header1"=>"value1"}, {"header2"=>"value2"}]
all_records= [record1, record2]

And I want to create new database record and if data with same keys
(header1+header2) already exist I want to merge this rows

all_records.each do record
record.each |do| i
Record.create!(i)
Record.where(:header1 => i["header1"], :header2 => i["header2"]
).update(i)
Record.index({ header1: 1, header2:1 }, { unique: true, drop_dups: true
})
end
end
But when I run this code I am getting error Mongoid::Errors::Validations
And looks like code record.index({ header1: 1, header:2 }, { unique:
true, drop_dups: true })
does not do anything, because I still getting duplicated records in
database.
What is wrong with this code? Thank you for the help!

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Sep 18, 2014, 2:25:16 AM9/18/14
to rubyonra...@googlegroups.com
Should there be a space after header2:

Colin

> end
> end
> But when I run this code I am getting error Mongoid::Errors::Validations
> And looks like code record.index({ header1: 1, header:2 }, { unique:
> true, drop_dups: true })
> does not do anything, because I still getting duplicated records in
> database.
> What is wrong with this code? Thank you for the help!
>
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/2fccca9675eacfe7b8f57ddcfe4726ad%40ruby-forum.com.
> For more options, visit https://groups.google.com/d/optout.

Arthur Petrov

unread,
Sep 18, 2014, 2:46:31 AM9/18/14
to rubyonra...@googlegroups.com
Hi! Colin! Yes, should be a space after header2:
Record.index({ header1: 1, header2: 1 }, { unique: true, drop_dups:
true })
But even with the space it does not do anything I still getting
duplicated records
Reply all
Reply to author
Forward
0 new messages