0

Recently I had to create a couple of records in a non-rails app database table based on a previous record. It got me thinking of how would I do this in a rails app. 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. 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.

Thanks for any help.

John Cowan
  • 1,452
  • 5
  • 25
  • 39
  • 1
    [What is the easiest way to duplicate an activerecord record?](https://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record) – jvillian Oct 20 '20 at 22:15

1 Answers1

0

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. The copy is not yet saved to the database. Replace dup with clone if you're using an old version of Rails (<3.1).

In the second line, assign_attributes alters the attributes of the object, still without saving it to the database. 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. 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.

Ned
  • 16
  • 1