small medium large xlarge

Generic-user-small
08 Sep 2010, 21:50
Joost Saanen (6 posts)

When practicing a little (playtime, chapter 15) to add a feature for deleting a item from the cart, I was wondering if there is some better (optimal) solution then I did. The code below works although I am not feel really comfortable with it.

I am not happy with the save method (Is there better way to update the line_item?) in the remove_or_decrease_line_item method and I tried to delete the object from the array with the delete_if but that doesn’t seem to work:

line_items.delete_if { |item| item.id == line_item.id }

This code works:

in the cart I add the remove link, which points to the destroy action in the line_items_controller:

link_to "remove", line_item, :method => :delete

In the line_items_controller I added these lines:

@cart = current_cart
line_item = LineItem.find(params[:id])
@cart.remove_or_decrease_line_item(line_item)

The method in my cart model:

  def remove_or_decrease_line_item(line_item)
    if(line_item.quantity > 1)
       line_item.quantity -= 1
       line_item.save 
    else
       line_item.destroy
    end
  end  

Any thoughts on this?

Samr_small_pragsmall
09 Sep 2010, 01:24
Sam Ruby (634 posts)

For the first part, try:

line_items.each { |item| item.destroy if item.id == line_item.id }

As to your second question, consider moving @remove_or_decrease@ to be a method in the LineItem model, as there is no reference to the cart in it.

Generic-user-small
09 Sep 2010, 19:20
Joost Saanen (6 posts)

OK, I modify it a little:

line_item model

  def remove_or_decrease
    if(quantity > 1)
      self.quantity -= 1 
      self.save
    else
      self.destroy
    end
  end  

LineItemController:

  def destroy
    line_item = LineItem.find(params[:id])
    line_item.remove_or_decrease

    respond_to do |format|
      format.html { redirect_to(store_url) }
      format.xml  { head :ok }
    end
  end

Are there any improvements to make?

Generic-user-small
07 Mar 2011, 19:58
ubique (11 posts)

Which files are you referring to here as vague…..

Did you get it working?

You must be logged in to comment