Ruby on rails 清理控制器,更新购物车内的物品数量

Ruby on rails 清理控制器,更新购物车内的物品数量,ruby-on-rails,ruby,shopping-cart,Ruby On Rails,Ruby,Shopping Cart,大家好,我想知道是否有人可以帮助我,我需要清理这个控制器,因为如果已经存在的话,只需更新一个项目数量的结果代码似乎太复杂了 class LineItemsController < ApplicationController def create @product = Product.find(params[:product_id]) if LineItem.exists?(:cart_id => current_cart.id) item = Lin

大家好,我想知道是否有人可以帮助我,我需要清理这个控制器,因为如果已经存在的话,只需更新一个项目数量的结果代码似乎太复杂了

class LineItemsController < ApplicationController  
  def create
   @product = Product.find(params[:product_id])
    if LineItem.exists?(:cart_id => current_cart.id)
      item = LineItem.find(:first, :conditions => [ "cart_id = #{@current_cart.id}"])
      LineItem.update(item.id, :quantity => item.quantity + 1)
    else  
     @line_item = LineItem.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
     flash[:notice] = "Added #{@product.name} to cart."
  end
  redirect_to root_url
 end  
end
class LineItemsControllercurrent\u cart.id)
item=LineItem.find(:first,:conditions=>[“cart\u id={@current\u cart.id}])
LineItem.update(item.id,:quantity=>item.quantity+1)
其他的
@line\u item=LineItem.create!(:购物车=>当前购物车,:产品=>@product,:数量=>1,:单价=>@product.price)
flash[:notice]=“将#{@product.name}添加到购物车。”
结束
将\u重定向到根\u url
结束
结束
`

由于总是非常感谢任何帮助,代码应该是相当自解释的,谢谢:)


PS在这里发布了它,而且它在这里看起来有点滑稽

我想你要找的是:

class LineItemsController < ApplicationController
  def create
    @product = Product.find(params[:product_id])
    item = LineItem.find_or_initialize_by_cart_id(:cart_id => current_cart.id, :cart => current_cart, :product => @product, :quantity => 0, :unit_price => @product.price)
    item.increment! :quantity
    flash[:notice] = "Added #{@product.name} to cart."
    redirect_to root_url
  end
end
class LineItemsController当前购物车id,:购物车=>当前购物车,:product=>@product,:quantity=>0,:单价=>@product.price)
item.increment!:量
flash[:notice]=“将#{@product.name}添加到购物车。”
将\u重定向到根\u url
结束
结束

因此,它所做的就是调用
LineItem.find\u by\u cart\u id(当前的\u cart.id)
,如果它不存在,它将使用传递的属性创建它。我认为您无法回避的一个问题是在进行数据库调用(查找或创建)后更新数量,因为您必须确定资源是刚刚创建的还是已经存在。

也许您应该更具体一点,就个人而言,我不喜欢“清理我的代码”问题。@Joseph Silvashy,我不同意。这不是“清理我的代码”,而是“如何更好地利用rails使我的代码看起来更干净”。学习更好的编程的一部分是让别人向您展示更好的方法。卡尔有足够的洞察力,知道他正在做的事情可以做得更好。我会用一些更原子化的方法来增加计数器:item.increment!:量您的另一个问题可以通过查找或初始化轻松解决。您可以询问item.new_记录?如果你感兴趣的话。@hurikhan77:好主意!我对rails还比较陌生,所以我不知道
increment
find_或_initialize_by_uu
感谢所有有用的评论和建议:)您可以通过使用count=0进行初始化,并执行“item.increment!:quantity”,而不管是否有新记录。increment的bang版本还将保存您的记录,因此您可以删除该行。