[英]Best way to return recently created object in ActiveRecord?
I'm creating an object that when called it will create an database record and I want this function to return the newly created object. This is what I got:我正在创建一个 object,调用它时会创建一个数据库记录,我希望这个 function 返回新创建的 object。这就是我得到的:
data = {foo: 'foo', bar: 'bar'}
Dummy.new(data).save! # true
Dummy.last # newest record in the database
I'm concerned about what this would mean when there are more than one sessions on the same database.我担心当同一数据库上有多个会话时这意味着什么。 Is there a sure-fire way of getting the record I just created?是否有可靠的方法来获取我刚刚创建的记录?
Just assign the instance you created to a variable:只需将您创建的实例分配给一个变量:
data = {foo: 'foo', bar: 'bar'}
dummy = Dummy.new(data)
dummy.save!
dummy # the record you just created
Or use create!
或者使用create!
instead of new
and save!
而不是new
并save!
like this:像这样:
data = {foo: 'foo', bar: 'bar'}
Dummy.create!(data) # returns the created instance or raises an error if not successful
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.