开发者

Save a new row based on existing activerecord object, setting id to nil didn't work

I am trying to save 2 rows, the 2nd row based on the 1st row:

user = User.new(....)
user.save!

user.id = nil
user.name = "d开发者_JS百科ifferent name"
user.save!

This doesn't create a 2nd row, what should I do?


The problem is that Rails thinks you're trying to change an instance that is already saved to the database, rather than create a new one. What you want to do is clone the original record, and it should work. Here are the Rails docs on using clone.

# First instance
user = User.create(...params...)

# New instance (no need to set id = nil)
user2 = user.clone
user2.name = "different name"
user2.save!


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 you need.

If you want to repeat the conditions for all of these except the name, you could just save your repeated params to an instance variable and set the non-repeating attributes on each create. Something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜