我正在使用Instant-Rails 2.0并使用Rails第3版的Agile Web Development的Depot示例项目。
我的问题是:当客户通过购物车和订单表单下订单时,我需要更新产品列数量表。 例如:如果我有10本书(价值“10”存储在具有产品特定ID的产品表中)并且客户想要2本书,在订单之后我希望我的项目更新可用书籍的数量值,把它减少到8本书。
我尝试在store_controller.rb
中添加add_to_cart方法:
def add_to_cart
product = Product.find(params[:id])
@quantity = Product.find(params[:quantity])
@cart = find_cart
@current_item = @cart.add_product(product)
@removed = Product.remove_q(@quantity)
respond_to do |format|
format.js if request.xhr?
format.html {redirect_to_index}
end
rescue ActiveRecord::RecordNotFound
logger.error("Product not found #{params[:id]}")
redirect_to_index("invalid product!")
end
其中remove_q
是product.rb
模型的方法:
def self.remove_q(quantity)
@quantity = quantity - 1
end
当我点击“添加到购物车”按钮时,RoR在控制台中给出了“产品未找到”错误。我做错了什么?
更新:感谢ipsum的回答。解决方案是在成功订购后减少产品数量。这是save_order
的方法store_controller.rb
:
def save_order
@cart = find_cart
@order = Order.new(params[:order])
@order.add_line_items_from_cart(@cart)
@recipient = 'email@notify.com'
@subject = 'Order'
email = Emailer.create_confirm(@order, @recipient, @subject)
email.set_content_type("text/html")
@cliente = sent
if @order.save
Emailer.deliver(email)
return if request.xhr?
session[:cart] = nil
redirect_to_index("Thank you")
else
render :action => 'checkout'
end
结束
请注意Emailer
是成功订购后通过电子邮件发送通知的模型,购物车由许多line_items制作,这些line_items是客户添加到购物车的产品。成功订购后,如何减少购物车中的产品数量?如何从购物车中提取产品?
模型cart.rb
:
class Cart
attr_reader :items
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product)
@items << current_item
end
current_item
end
def total_price
@items.sum { |item| item.price}
end
def total_items
@items.sum { |item| item.quantity }
end
end
和模型line_item.rb
:
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
def self.from_cart_item(cart_item)
li = self.new
li.product = cart_item.product
li.quantity = cart_item.quantity
li.total_price = cart_item.price
li
end
end
答案 0 :(得分:3)
您尝试通过数量查找产品。 但“查找”需要主键
而不是:
@quantity = Product.find(params[:quantity])
试试这个:
@quantity = product.quantity
更新:
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@current_item = @cart.add_product(product)
product.decrement!(:quantity, params[:quantity])
respond_to do |format|
format.js if request.xhr?
format.html {redirect_to_index}
end
rescue ActiveRecord::RecordNotFound
logger.error("Product not found #{params[:id]}")
redirect_to_index("invalid product!")
end