Save new line based on existing activerecord object, setting id on nil does not work

I am trying to save 2 lines, 2nd line on 1st line:

user = User.new(....) user.save! user.id = nil user.name = "different name" user.save! 

This does not create a second line, what should I do?

+4
source share
2 answers

The problem is that Rails believes that you are trying to modify an instance that is already stored in the database, rather than creating a new one. What you want to do is clone the original record, and it should work. Here are the Rails docs when using the clone .

 # First instance user = User.create(...params...) # New instance (no need to set id = nil) user2 = user.clone user2.name = "different name" user2.save! 
+3
source
 user = User.new( :name => 'whatever') user.save! user = User.new( :name => 'other name') user.save! 

or even better, just do:

 User.create( :name => 'first user name' ) User.create( :name => 'second user name' ) 

... for as many users as possible.

If you want to repeat the conditions for all of them except the name, you can simply save your duplicate parameters in an instance variable and set non-duplicate attributes for each creation. Sort of:

 attributes = { :gender => :male, :age => 18 } User.create( :name=> 'John', attributes } User.create( :name=> 'Fred', attributes } 
+1
source

Source: https://habr.com/ru/post/1342482/


All Articles