Rails:如果一个失败,则回滚所有事务

时间:2017-08-14 16:32:15

标签: ruby-on-rails transactions

所以我有这个配置

class Post < ActiveRecord::Base
has_many :photo_albums

class PhotoAlbum < ActiveRecord::Base
has_many :photos

我想做以下

@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

现在我想要的是,如果@ post.save失败,那么photo_albums的所有交易,照片都应该回滚。

3 个答案:

答案 0 :(得分:0)

您只需添加if过滤器row1 <- c(-11,-10,-9,-7,0,3,15) row2 <- c(-13,-12,-11,2,0,-7,14) time_list <- rbind(row1,row2) > time_list [,1] [,2] [,3] [,4] [,5] [,6] [,7] row1 -11 -10 -9 -7 0 3 15 row2 -13 -12 -11 2 0 -7 14 time_list[time_list<0] <- NA > time_list [,1] [,2] [,3] [,4] [,5] [,6] [,7] row1 NA NA NA NA 0 3 15 row2 NA NA NA 2 0 NA 14 new_time_list <- time_list[,colSums(is.na(time_list))<nrow(time_list)] > new_time_list [,1] [,2] [,3] [,4] row1 NA 0 3 15 row2 2 0 NA 14 并编写代码块,只有在保存if @post.save时才能创建photo_albumphotos

@post

答案 1 :(得分:0)

使用ActiveRecord::Base.transaction

请参见this literature

答案 2 :(得分:0)

简单。

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