Ruby on rails 添加到今天rails 3.2创建的购物车
我的数据库是postgresql,使用rails 3.2.13,Ruby on rails 添加到今天rails 3.2创建的购物车,ruby-on-rails,ruby,postgresql,Ruby On Rails,Ruby,Postgresql,我的数据库是postgresql,使用rails 3.2.13, “将\u添加到\u购物车”方法未按预期工作, 我想添加到今天创建的购物车中,如果没有创建,则创建, 但它不会创建新的购物车,有时会添加到2-3天前创建的购物车中, 我的代码有什么问题 class Cart < ActiveRecord::Base has_many :line_items scope :from_today, where("created_at >= ? AND created_at <=
“将\u添加到\u购物车”方法未按预期工作,
我想添加到今天创建的购物车中,如果没有创建,则创建,
但它不会创建新的购物车,有时会添加到2-3天前创建的购物车中,
我的代码有什么问题
class Cart < ActiveRecord::Base
has_many :line_items
scope :from_today, where("created_at >= ? AND created_at <= ?",
Time.zone.now.beginning_of_day,
Time.zone.now.end_of_day)
def self.add_to_cart(user_id)
cart = Cart.from_today.first_or_create
line_item = cart.line_items.where(user_id: user_id).first_or_initialize
line_item.amount += 1
line_item.save
end
end
class购物车 范围:从今天开始,其中(“created_at>=”和created_at我的第一个猜测是你的范围内日期的格式。现在它将返回:
Time.zone.now.beginning_of_day
=> Mon, 28 Apr 2014 00:00:00 UTC +00:00
但在数据库查询中,您需要它的格式为:
Time.zone.now.beginning_of_day.to_s(:db)
=> "2014-04-28 00:00:00"
您可能还需要用单引号将时间括起来-进行测试并查看。似乎您的范围内有“动态数据”。请查看以了解发生了什么
您的作用域在初始化过程中执行,但需要在运行时执行。解决方法是:
要在作用域中使用lambda:scope:from_today,->{where(…)}
避免使用作用域并使用类方法:
def self.from_今日
其中(…)
结束
此外,在查询范围时,最好将数组或范围作为值传递:where(创建时间:(Time.zone.now.start\u of_day)…(Time.zone.now.end\u of_day))
尝试将范围更改为:where(创建时间:(Time.zone.now.start\u of_day)…(Time.zone.now.end\u of_day))
能否尝试将where
查询封装在lambda函数中,如scope:from_today,->{where(…)}
@SergeyKishenin好的,我会试试