Rails not rolling back transaction after failed save()

后端 未结 2 1601
刺人心
刺人心 2021-01-13 19:18

I have this domain model: A user has group of items, and the state of the items can fail a validation.

Validation works fine, and I even see exceptions get called wh

2条回答
  •  广开言路
    2021-01-13 19:50

    Adding an item to the collection saves it immediately (unless the user is unsaved). The call to save creates its own transaction and that is what is rolled back, not the transaction in which the item is saved

    You could force everything into the same transaction by creating one explicitly.

    begin
      User.transaction do
        @user.items << item
        @user.save!
        render :json => {}, :status => :ok
      end
    rescue ActiveRecord::RecordInvalid
      render :json => {:status => :error, :errors => item.errors}, :status => :bad_request
    end
    

提交回复
热议问题