【问题标题】:Clean Up Controller, Update Item Quantity within Cart清理控制器,更新购物车内的物品数量
【发布时间】:2011-02-28 10:44:21
【问题描述】:

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

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

`

一如既往地非常感谢任何帮助,代码应该是相当不言自明的,谢谢:)

PS 把它贴在这里,看起来有点搞笑http://pastie.org/994059

【问题讨论】:

  • 也许你应该更具体一点,我个人不喜欢“清理我的代码”问题。
  • @Joseph Silvashy,我不同意。这不是“清理我的代码”,而是“如何更好地利用 Rails 使我的代码看起来更干净” 学习更好的编程的一部分是让某人向您展示更好的做事方式。卡尔有足够的洞察力,知道他正在做的事情可以通过某种方式做得更好。

标签: ruby-on-rails ruby shopping-cart


【解决方案1】:

我认为您正在寻找的是:

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

所以它的作用是调用LineItem.find_by_cart_id(current_cart.id),如果它不存在,它会使用传递的属性创建它。我认为您无法解决的一个问题是在进行数据库调用(查找 - 或 - 创建)后更新数量,因为您必须确定资源是刚刚创建还是已经存在。

【讨论】:

  • 我会使用一些更原子的方式来增加计数器:item.increment! :数量。 find_or_initialize_by 可以轻松解决您的其他问题。你可以问 item.new_record 吗?如果你有兴趣。
  • @hurikhan77:好主意!我对 Rails 还比较陌生,所以我不知道 incrementfind_or_initialize_by_
  • 感谢所有有用的 cmets 和建议 :)
  • 您可以通过使用 count=0 初始化并执行 "item.increment! :quantity" 来进一步精简它,无论是否有新记录。爆炸版本的增量也将保存您的记录-因此您可以终止该行。
猜你喜欢
  • 1970-01-01
  • 2015-06-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2013-09-24
  • 2014-09-12
  • 1970-01-01
相关资源
最近更新 更多