简体   繁体   English

返回最近在 ActiveRecord 中创建的 object 的最佳方式?

[英]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!而不是newsave! 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.

相关问题 从活动记录关系中提取对象的最佳方法 - best way to extract object from an activerecord relation 在memcached中存储ActiveRecord对象的最佳方法是什么? - What is the best way to store an ActiveRecord object in memcached? 返回具有关联的 ActiveRecord 对象的干净方法 - Clean way to return ActiveRecord object with associations 使用空值创建的ActiveRecord对象 - ActiveRecord object created with null values 将 ActiveRecord 对象的所有属性(id、created_at、updated_at 除外)设置为 nil 的最简单方法是什么? - What is the easiest way to set all attributes (except id, created_at, updated_at) of an ActiveRecord object to nil? ActiveRecord对象的最佳做法,该对象在保存时更新另一个ActiveRecord对象 - Best practice for an ActiveRecord object that updates another ActiveRecord object on save 如何编写ActiveRecord范围,该范围返回最近创建的2条属于其父级的记录? - How do I write an ActiveRecord scope that returns the most recently created 2 records that belong to their parent? 基于对象属性获取活动记录对象数组的唯一元素的最佳方法是什么? - What is the best way to get unique elements of an array of activerecord objects based on attributes of the object? ActiveRecord对象的未定义方法“ created_at” - undefined method `created_at' for ActiveRecord object 从链接更新ActiveRecord属性的最佳方法 - Best way to update an ActiveRecord attribute from a link
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM