英文:
Create an object from ActiveRecord format
问题
以下是代码部分的翻译:
In trying to debug an issue that's appearing in production, I would like to copy some of the live data into my local database.
To begin with, I'm just trying to copy the latest two records.
payments = Payment.all[-2..-1]
请问您需要对其他部分进行翻译吗?
英文:
In trying to debug an issue that's appearing in production, I would like to copy some of the live data into my local database.
To begin with, I'm just trying to copy the latest two records.
payments = Payment.all[-2..-1]
Here is the return. I've censored most of the info for client and customer privacy.
[#<Payment id: 1400, payment_number: "###", user_id: ###, project_id: 85, phase_id: 155, amount: "500", notes: nil, status: "complete", created_at: "2023-03-16 16:50:23.434401000 -0400", updated_at: "2023-03-16 16:50:23.447559000 -0400", description: "###", processed_at: nil, payout_category: "manual">, #<Payment id: 1402, payment_number: "###", user_id: ###, project_id: nil, phase_id: nil, amount: nil, notes: "###", status: "incomplete", created_at: "2023-03-17 03:02:56.445550000 -0400", updated_at: "2023-03-20 11:42:56.153214000 -0400", description: "###", processed_at: nil, payout_category: "hyperwallet">]
In the past, I've successfully copied records by manually pasting the data into a notepad. Then I replace the pointy braces "<>" with curly brackets "{}", and delete the id attribute. This creates a hash that I can iterate across to populate a new record.
It seems like Rails would have a better way to read such a record in this format, since that's the way it spits them out. Is there a less time-consuming and error-prone way to create records in the console when given input in ActiveRecord format?
Thanks in advance for any insight.
答案1
得分: 1
你可以使用.dup
来复制具有空白ID的记录,然后使用.upsert_all
来插入它们。如果你在database.yml
中设置了两个数据库连接,那么可以使用这个参考来获取这些连接。
ActiveRecord::Base.establish_connection(:productions)
dupes = Payment.all[-2..-1].map {|p| p.dup}
ActiveRecord::Base.establish_connection(:development)
Payment.upsert_all(dupes)
英文:
You could use .dup
to make copies of the records with nil ids, then .upsert_all
to insert them. If you have both DB connections setup in your database.yml then you can use that reference for the connections.
ActiveRecord::Base.establish_connection(:productions)
dupes = Payment.all[-2..-1].map {|p| p.dup}
ActiveRecord::Base.establish_connection(:development)
Payment.upsert_all(dupes)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论