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

Ruby on rails Rails:如果一个事务失败,则回滚所有事务,ruby-on-rails,transactions,Ruby On Rails,Transactions,所以我有这个配置 class Post < ActiveRecord::Base has_many :photo_albums class PhotoAlbum < ActiveRecord::Base has_many :photos 现在我想要的是,如果@post.save失败,那么相册、照片的所有事务都应该回滚 您只需添加一个if过滤器if@post.save,并编写代码块,仅当@post已保存时,才能创建相册和照片 @post = Post.new(post_params

所以我有这个配置

class Post < ActiveRecord::Base
has_many :photo_albums

class PhotoAlbum < ActiveRecord::Base
has_many :photos

现在我想要的是,如果@post.save失败,那么相册、照片的所有事务都应该回滚

您只需添加一个if过滤器
if@post.save
,并编写代码块,仅当
@post
已保存时,才能创建
相册和
照片

@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

研究如何使用
ActiveRecord::Base.transaction

请参阅。

简单

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

实际上,我的意思是在任何保存或创建失败时回滚所有事务。为什么要回滚失败的事务,而不是跳过它。。保存一组数据库调用suse
@post.photo\u albums.new(…)
,而不是create,因为必须先保存父级。然后只需在父级(
@post
)上调用
save
,它将触发相册的保存
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