1

Does rails have a way to insert records from a model instance? Something like User.create(user)?

Ron Garrity
  • 1,383
  • 2
  • 13
  • 25
  • 1
    Possible duplicate with http://stackoverflow.com/questions/60033/what-is-the-easiest-way-to-duplicate-an-activerecord-record – Baldrick Jan 31 '12 at 16:22

2 Answers2

1

You would just use user.save assuming that user is an instance of User. AR knows whether to insert or update.

UPDATE (see comments)

This seemed to be a clone of a record issue, so the answer was to use dup method to create a shallow clone of the object.

Bangline
  • 890
  • 5
  • 11
  • That's not working as I expected. For testing purposes, I tried the following: u = User.find(1); u.id = nil; u.save and it tries to update updated_at where users.id is NULL, which kind of makes sense. Am I don't something wrong. I'm selecting this object from User and so it'll always try to update it, when I want to insert it as a new record. – Ron Garrity Jan 31 '12 at 16:14
  • Why are you setting the id as nil ? You would normally create a new instance using `user = User.new()` and then call `user.save`. By doing a `find` you are selecting an existing record in the database, then setting the id to nil, calling `save` will of course try to save where `id` = nil. Which will blow up. Are you trying to clone a record from the db and save that as a new record? – Bangline Jan 31 '12 at 16:21
  • 1
    should say if you are trying to clone use `dup` that creates a copy of the re4cord without saving it, (Rails 3+) – Bangline Jan 31 '12 at 16:23
  • Yes. I want to do a deep clone on a few records, modify them a little, remove a few under some certain condition, and save them as new records. – Ron Garrity Jan 31 '12 at 16:23
  • yep use `dup` just watch for the deep clone, you may have to check the associations and add them manually. – Bangline Jan 31 '12 at 16:26
  • Hmm... ok. If you update your answer w/ the dup, I'll mark this as the answer. Thanks a lot. – Ron Garrity Jan 31 '12 at 16:28
1

You might want to try FactoryGirl to create objects: https://github.com/thoughtbot/factory_girl

three
  • 8,262
  • 3
  • 35
  • 39