开发者

ActiveRecord Transaction and return the saved id of the model

开发者 https://www.devze.com 2023-04-05 05:05 出处:网络
I want to use ActiveRecord transactions to s开发者_C百科ave three of my models. I was able to find some good tutorials like

I want to use ActiveRecord transactions to s开发者_C百科ave three of my models. I was able to find some good tutorials like

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

http://ar.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

But my question is, I want to get my first model's id and save it as a foreign key with my second model. As far as I know I couldn't do this because I cannot get the saved id until the transaction commits.

Does anyone have a better solution or workaround for this problem? I'm using Rails 2.3.8.


Generally when you need to save objects with relationships, it means you should use accepts_nested_attributes_for. See doc here.

It's by far the cleanest and the best way to proceed.


What about:

SomeClass.transaction do
  first_record = SomeClass.create(... vars ...)
  second_record = SomeClass.create(... vars ...)
  third_record = SomeClass.create(... vars ...)

  second_record.update_attributes(:related_id=>first_record.id)
  third_record.update_attributes(:related_id=>second_record.id)
end

That would create the objects, and assign the ids in one overall transaction. If it fails, all records should be rolled back, including the creation of the records in the first place.

0

精彩评论

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