我正在Rails中构建一个具有特定销售模型的商店。我需要允许用户每30天只添加3个项目到他的订单。30天计数器应该从添加第一个order_item开始。一旦30天到期,用户将能够添加3个订单。如果30天没有过去,例如,用户添加了两个order_item,他仍然可以在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
看来你的问题是双重的。
首先,您要在第45行使用DateTime.current
(这是谈论"now"的正确方式)
其次,错误实际上是说你不能减去日期和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
...