简体   繁体   English

Rails:如果一个交易失败,则回滚所有交易

[英]Rails: rollback all transactions if one fails

So I have this configurations 所以我有这个配置

class Post < ActiveRecord::Base
has_many :photo_albums

class PhotoAlbum < ActiveRecord::Base
has_many :photos

and I want to do the following 我想做以下事情

@post = Post.new(post_params)
@photo_album = @post.photo_albums.create(name: 'album name')
@photo_urls = params[:photo_urls]
@photo_urls.each do |pu|
 @photo_album.photos.create(url: pu)
end
@post.save

Now what I want is that, if @post.save fails then all transactions of photo_albums, photos should rollback. 现在我想要的是,如果@ post.save失败,则所有photo_albums事务都应回滚照片。

you can just add an if filter if @post.save and write the code block to create photo_album and photos only if the @post is saved 您可以仅在if @post.save添加if过滤器if @post.save并仅在保存@post情况下编写代码块以创建photo_albumphotos

@post = Post.new(post_params)
if @post.save
  @photo_album = @post.photo_albums.create(name: 'album name')
  @photo_urls = params[:photo_urls]
  @photo_urls.each do |pu|
   @photo_album.photos.create(url: pu)
  end 
else
  # handle @post.save fail
end

Look into using ActiveRecord::Base.transaction . 调查使用ActiveRecord::Base.transaction

See this literature . 请参阅此文献

Simple. 简单。

ActiveRecord::Base.transaction do
  @post = Post.new(post_params)
  @photo_album = @post.photo_albums.create(name: 'album name')
  @photo_urls = params[:photo_urls]
  @photo_urls.each do |pu|
    @photo_album.photos.create(url: pu)
  end
  @post.save
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM