簡體   English   中英

Rails應用中的回滾事務錯誤

[英]Rollback transaction error in rails app

我正在嘗試按照本教程在Rails應用程序中構建購物車系統。 一切正常,但是當我嘗試添加產品(在我的情況下是椅子)時,彈出的窗口顯示“無效”,終端沒有顯示任何錯誤,除了“ 回滾事務”

我的產品型號

class Chair < ApplicationRecord
    mount_uploader :image, ImageUploader
    mount_uploader :previewo, PreviewoUploader
    mount_uploader :previewt, PreviewtUploader
    mount_uploader :previewth, PreviewthUploader
    has_many :order_items
    validates :description, presence: true, length: { maximum: 600 }
    default_scope { where(active: true) }
end

order.rb

class Order < ApplicationRecord
  belongs_to :order_status
    belongs_to :order_status
  has_many :order_items
  before_create :set_order_status
  before_save :update_subtotal

  def subtotal
    order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum
  end
private
  def set_order_status
    self.order_status_id = 1
  end

  def update_subtotal
    self[:subtotal] = subtotal
  end
end

order_item.rb

class OrderItem < ApplicationRecord
  belongs_to :chair
  belongs_to :order

  validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
  validate :chair_present
  validate :order_present

  before_save :finalize

  def unit_price
    if persisted?
      self[:unit_price]
    else
      chair.price
    end
  end

  def total_price
    unit_price * quantity
  end

private
  def chair_present
    if chair.nil?
      errors.add(:chair, "is not valid or is not active.")
    end
  end

  def order_present
    if order.nil?
      errors.add(:order, "is not a valid order.")
    end
  end

  def finalize
    self[:unit_price] = unit_price
    self[:total_price] = quantity * self[:unit_price]
  end
end

OrderStatus.rb

class OrderStatus < ApplicationRecord
    has_many :orders
end

終端輸出

Started POST "/order_items" for 127.0.0.1 at 2018-07-05 22:42:29 +0530
Processing by OrderItemsController#create as JS
  Parameters: {"utf8"=>"✓", "order_item"=>{"quantity"=>"1", "chair_id"=>"3"}, "commit"=>"Add to Cart"}
   (0.2ms)  begin transaction
  Chair Load (2.0ms)  SELECT  "chairs".* FROM "chairs" WHERE "chairs"."active" = ? AND "chairs"."id" = ? LIMIT ?  [["active", "t"], ["id", 3], ["LIMIT", 1]]
   (0.2ms)  rollback transaction
  Rendering order_items/create.js.erb
  Rendered order_items/create.js.erb (1.2ms)
Completed 200 OK in 77ms (Views: 14.9ms | ActiveRecord: 2.4ms)

在我看來,order_items參數中的椅子不存在。 如果您轉到rails console並輸入Chair.find(3) 我希望椅子不存在。 您在order_items中對chair_present的驗證正在阻止事務進行,因為主席還不存在。 您需要先創建椅子,然后再將其關聯。

將您的order_items_controller更改為此以驗證:

  def create
    @order = current_order
    @order_item = @order.order_items.new(order_item_params)
    if @order.save
        session[:order_id] = @order.id
      else
        puts "Order Item failed to save because #{@order.errrors}"
    end
  end

那么您應該在控制台上看到一個輸出,告訴您為什么保存失敗。

暫無
暫無

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

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