Clean Up Controller, Update Item Quantity within Cart

Posted by Karl Entwistle on Stack Overflow See other posts from Stack Overflow or by Karl Entwistle
Published on 2010-06-06T18:34:34Z Indexed on 2010/06/06 18:42 UTC
Read the original article Hit count: 313

Filed under:
|
|

Hi guys I was wondering if anyone could help me out, I need to clean up this controller as the resulting code to simply update an items quantity if it already exists seems way too complex.

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

`

As always any help is much appreciated, the code should be fairly self explanatory, thanks :)

PS posted it here as well as it looks a bit funny on here http://pastie.org/994059

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby