我正在Rails中建立一个具有特定销售模型的商店。我需要允许用户每30天只向其订单添加3个项目。 30天计数器应该在添加第一个order_item时开始。一旦30天到期,用户将能够添加3个订单。如果30天没有通过,例如,用户添加了两个order_items,他仍然可以在30天内再添加一个order_item。因此,如果用户尝试添加超过3个项目以显示错误消息,并忽略将order_items保存到current_user的订单。
我现在在日志中的日志中收到此错误:
TypeError (expected numeric):
app/models/order_item.rb:46:in `only_3_items_in_30_days'
控制器:
class OrderItemsController < ApplicationController
def create
@item = OrderItem.new(order_item_params)
session[:order_id] = current_order.id
if @item.save
respond_to do |format|
format.js { flash[:notice] = "ORDER HAS BEEN CREATED." }
end
else
redirect_to root_path
end
end
end
def update
@order = current_order
@order_item = @order.order_items.find(params[:id])
@order_item.update_attributes(order_item_params)
@order_items = @order.order_items
end
def destroy
@order = current_order
@order_item = @order.order_items.find(params[:id])
@order_item.destroy
@order_items = @order.order_items
end
private
def order_item_params
base_params = params.require(:order_item)
.permit(:quantity, :product_id, :user_id)
base_params.merge(order: current_order)
end
order_item.rb
class OrderItem < ActiveRecord::Base
belongs_to :product
belongs_to :order
validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 }
validate :product_present
validate :order_present
validate :only_3_items_in_30_days
before_save :finalize
def unit_price
if persisted?
self[:unit_price]
else
product.price
end
end
def total_price
unit_price * quantity
end
private
def product_present
if product.nil?
errors.add(:product, "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
def only_3_items_in_30_days
now = Date.new
days_since_first = now - order.first_item_added_at
if order.order_items.count > 2 && days_since_first < 30
errors.add(:base, 'only 3 items in 30 days are allowed')
end
true # this is to make sure the validation chain is not broken in case the check fails
end
end
答案 0 :(得分:0)
看起来你的问题是双重的。
首先,您要对第45行使用DateTime.current
(这是正确的谈论方式&#34;现在&#34;`
其次,错误实际上是说您无法减去日期和nil
。所以你需要先检查一切。
def only_3_items_in_30_days
unless order.first_item_added_at
return true #(or whatever you want to do in this case)
end
now = Time.current
days_since_first = now - order.first_item_added_at
...