[英]Rails. Save parent, before save children
When I try create line_item, I get this error: ActiveRecord::RecordNotSaved (You cannot call create unless the parent is saved). 当我尝试创建line_item时,出现以下错误:ActiveRecord :: RecordNotSaved(除非保存了父级,否则无法调用create)。
When I wrong? 当我错了吗? How fix it? 如何解决?
line_items controller line_items控制器
def create
@product = Product.find_by_id(params[:line_item][:product_id])
@cart = current_cart
@line_item = @cart.add_product(line_item_params)
end
cart model 推车型号
has_many :line_items, dependent: :destroy
def add_product(line_item_args)
current_line_item.quantity += line_item_args[:quantity].to_i
current_line_item.save
if current_item
current_item.quantity += line_item.quantity.to_i
else
current_item = line_items.create!(line_item_args)
end
current_item
end
UPD UPD
working helper method current_cart from application controller. 应用程序控制器中的工作辅助方法current_cart。 problem was in it. 问题出在其中。
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
我不知道您如何使用购物车,但是我确定当前的购物车未在数据库中保存,请检查其是否正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.