這裏有一個快速的測試,我在我的模型製作:
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
因爲在數組的第一個元素將是一個空字符串
4. records = parsed.map { |serialized_record| JobUser.new(eval "{ #{serialized_record} }") }
那麼你或許應該運行類似records.each { |record| record.save }
請注意,您應該用您的型號名稱替換JobUser
。 關鍵是你必須解析字符串並將其插回到數據庫中
祝你好運!
謝謝你的回答! 如果我爲模型屬性之一添加了「#
Dmitri
謝謝!這非常好!乾杯! :) – Dmitri
小心用雙引號,我在包含日期的時候遇到了問題,日期時間裏有雙引號,但是通過執行'str ='blah''好像有效 –