我正在尝试通过遵循此tutorial在Rails应用程序中构建购物车系统。一切正常,但是当我尝试添加产品(在我的情况下是椅子)时,弹出的窗口显示“无效”,终端显示除 Rollback Trasaction 之外的其他任何错误。
我的产品型号
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)
答案 0 :(得分:0)
在我看来,order_items参数中的椅子不存在。如果您进入Rails控制台并输入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
然后,您应该在控制台上看到一个输出,告诉您为什么它无法保存。