簡體   English   中英

ActiveRecord 在 Rails 中回滾

[英]ActiveRecord rollback in Rails

Rails 5.2

我有一個部分:

views/authors/_add_author_comment.html/slim

= form_for :author_note, url: author_notes_url, method: :post do |f|
  = f.hidden_field :author, value: @book.author
  = f.text_area :comment
  button.btn.btn-primary type="button"
  = f.submit t('authors.show.submit_comment')   

在我的控制器/author_notes_controller.rb 中,我有:

def create
  @author_note = AuthorNote.new(author: params[:author_note][:author], user_id: current_user.id, comment: params[:author_note][:comment])
  @author_note.save
end

當表單顯示(大視圖的一部分)時,我填寫了評論,然后單擊“提交評論”,評論沒有保存。 在控制台中,我看到以下內容:

AuthorNotesController#create as HTML 處理

Parameters: {"utf8"=>"✓", "authenticity_token"=>"Jju1cpsLjXLY/TaF9p/Zkh8JQ/+KajjxwQHgNU4tNU9bjL8BiZQ8xL3S7ske1KqflOPHVaB9UTWRvgxNqzLd7Q==", "author_note"=>{"author"=>"John Dow", "comment"=>"This is a test"}, "commit"=>"Save Note"}
User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = '5' ORDER BY `users`.`id` ASC LIMIT 1
↳ app/controllers/author_notes_controller.rb:23
User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = '5' LIMIT 1
↳ app/controllers/author_notes_controller.rb:23
 (0.2ms)  BEGIN
↳ app/controllers/author_notes_controller.rb:28
 (0.1ms)  ROLLBACK
↳ app/controllers/author_notes_controller.rb:28
No template found for AuthorNotesController#create, rendering head :no_content
Completed 204 No Content in 60ms (ActiveRecord: 10.6ms)

為什么 ActiveRecord 回滾,而不是將注釋保存到 author_notes 表?

解析度:

author_note.rb model,我有:belongs_to:book,我把它注釋掉了

您沒有包含您的AuthorNote model,可能有一些驗證約束會阻止author_note被保存。

您的代碼也不處理驗證錯誤,因此您可能想要這樣做。 但是您可以簡單地檢查以下錯誤:

def create
  @author_note = AuthorNote.new(author: params[:author_note][:author], user_id: current_user.id, comment: params[:author_note][:comment])
  @author_note.save
  # puts works too
  logger.debug "author_note save error: #{@author_note.errors.full_messages.join(' ')}"
end

這很可能是因為 rails 5 默認需要 belongs_to 關聯。

這意味着從 rails > 5,如果您在 model 上定義belongs_to並且相應的記錄不存在。 在這種情況下, AuthorNote 記錄中的book_id應該為 nil。 ActiveRecord 將出錯並回滾事務。

要解決此問題,您可以將其設置為可選,而不是一起注釋掉belongs_to關系(因為刪除關系可能會破壞系統)

class AuthorNote < ApplicationRecord
  belongs_to :book, optional: true
end

使用! 連同將顯示錯誤消息Object.save! Object.create!

def create
   @author_note = AuthorNote.new(author: params[:author_note][:author], user_id: current_user.id, comment: params[:author_note][:comment])
   @author_note.save!
end

或者

def create
   @author_note = AuthorNote.create!(author: params[:author_note][:author], user_id: current_user.id, comment: params[:author_note][:comment])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM