简体   繁体   English

Rails 控制台:使用现有记录创建新记录

[英]Rails Console: Create a New Record Using an Existing Record

Recently I had to create a couple of records in a non-rails app database table based on a previous record.最近,我不得不根据以前的记录在非 Rails 应用程序数据库表中创建几条记录。 It got me thinking of how would I do this in a rails app.这让我开始思考如何在 Rails 应用程序中做到这一点。 I tried a couple of things in the Console, but nothing works.我在控制台中尝试了几件事,但没有任何效果。

I want to do something like this:我想做这样的事情:

001> user = User.new(User.first)

I know this doesn't work but hopefully it will show you what I an thinking.我知道这行不通,但希望它能告诉你我的想法。 User is a large table/model, and I only need to change a few fields. User是一个大表/模型,我只需要更改几个字段。 So, if I can set up a new record with the same values in User.first , I can then edit the fields I need to before .save -ing the record.因此,如果我可以在User.first设置具有相同值的new记录,那么我可以在.save记录之前编辑我需要的字段。

Thanks for any help.谢谢你的帮助。

I think what you want is:我想你想要的是:

user = User.first.dup
user.assign_attributes(email: "myemail@test.test")
user.save

The first line uses dup to create a copy of the object.第一行使用dup创建对象的副本。 The copy is not yet saved to the database.该副本尚未保存到数据库中。 Replace dup with clone if you're using an old version of Rails (<3.1) . 如果您使用的是旧版本的 Rails (<3.1) ,请将dup替换为clone

In the second line, assign_attributes alters the attributes of the object, still without saving it to the database.在第二行中, assign_attributes更改对象的属性,但仍不将其保存到数据库中。 If you were working with an object already saved in the database, you could use update instead of assign_attributes to change the attributes of the object and save the changes in one go.如果您正在使用已保存在数据库中的对象,则可以使用update而不是assign_attributes来更改对象的属性并一次性保存更改。 That won't work here, because we haven't saved our duplicate user yet.这在这里不起作用,因为我们还没有保存我们的重复用户。 More details on that here. 更多细节在这里。

The third line finally saves the new object to the database.第三行最后将新对象保存到数据库中。 It saves time to just do this once, at the end.最后只做一次可以节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM