Question

I've accidentally erased all the records from one my model.

Model.destroy_all

For the output I've received a large list for all the records that have been destroyed.

=> [#<Model id: 1, some_attribute: "Hello World">, #<Model id: 2, some_attribute: " Hello World 2">, etc etc etc] 

But, I've got it a text. Can I do anything, using IRB, to return the records back ?

This is very, VERY urgent! Any help is appreciated.

Thank you so much

Was it helpful?

Solution

The following script should do the trick:

require 'bigdecimal'

str = "#<Model id: 1, some_attribute: #<BigDecimal:4ba0730,'0.0',9(18)>, another_attribute: \"Hello World\">, #<Model id: 2, some_attribute: \" Hello World 2\">"

str.scan(/#?<(\w+) (.+?)>(?=, #|$)/) do |m|
    model = Object.const_get(m[0])
    m[1].gsub!(/#<BigDecimal:.+?('.+?').+?>/, "BigDecimal.new(\\1)")
    eval("model.create(#{m[1]})")
end

This also handles instances of BigDecimal. In case you need to handle other special types you can just add another call to gsub!.

OTHER TIPS

here's a quick test I made on my model:

1. pry(main)> output = JobUser.first(10).to_s

=> "[#<JobUser id: 10001, instagram_user_id: 297705889, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\">, #<JobUser id: 10002, instagram_user_id: 36823356, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\">, #<JobUser id: 10003, instagram_user_id: 509682835, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\"> ....

2.

parsed = output.gsub('#<', '').gsub('>', '').gsub(/^\[/, '').gsub(/\]$/, '').split('JobUser').map(&:strip)

=>

     "id: 10001, instagram_user_id: 297705889, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\",",
     "id: 10002, instagram_user_id: 36823356, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\",",
     "id: 10003, instagram_user_id: 509682835, job_id: 2, invited: true, created_at: \"2013-09-23 21:53:37\", updated_at: \"2013-09-23 21:53:37\"...

3. parsed.shift because the first element in array will be a blank string

4. records = parsed.map { |serialized_record| JobUser.new(eval "{ #{serialized_record} }") }

then you should probably run something like records.each { |record| record.save }

Please note that you should replace JobUser with your model name. The point is you'll have to parse the string and insert it back into database

good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top