Question

I have a Cart model which has_many line_items. I am trying to update the quantity attribute for a line_item object in a cart but it doesn't seem to be updating. I want the quantity to update and redirect right back to the same page. Below is my code, when I submit the form it just redirects to the same page with the quantity value unchanged

models

class LineItem < ActiveRecord::Base
  attr_accessible :cart_id, :product_id, :quantity, :unit_price, :product, :cart,
 :color_id, :size_id, :extra_id
      belongs_to :cart
      belongs_to :product
      belongs_to :color
      belongs_to :size
      belongs_to :extra
      validates :quantity, :presence => true

class Cart < ActiveRecord::Base
  attr_accessible :purchased_at
  has_many :line_items
  has_one :order

controllers

class LineItemsController < ApplicationController
  def new
    @line_item = LineItem.new
  end
  def create
    @line_item = LineItem.create!(params[:line_item].merge(:cart => current_cart))
    @line_item.update_attributes!(:unit_price => @line_item.item_price)

    redirect_to current_cart_url
  end
  def update
    @line_item = LineItem.find(params[:id])
    redirect_to current_cart_url
  end
end

class CartsController < ApplicationController
  def show
          @cart = current_cart
  end

  def update
          @cart = current_cart
          @line_item = @cart.line_items.find(params[:id]) 
          @line_item.update_attributes(:quantity => params[:quantity])
          redirect_to current_cart_url
  end     
end

routes

get 'cart' => 'carts#show', :as => 'current_cart'

carts/show

<% for line_item in @cart.line_items %>
<div class="row">
        <div class="span6">
               <%=h line_item.product.name %>
        </div>
        <div class="span2">
              <%= form_for @cart do |f| %>
                    <%= f.number_field :quantity, :value => line_item.quantity, class: "qty" %>
                    <%= f.hidden_field :line_item_id, :value => line_item.id %>
                    <%= f.submit "update" %>
              <% end %>
          </div>
          <div class="span2"><%= number_to_currency(line_item.unit_price) %></div>
          <div class="span2"><%= number_to_currency(line_item.full_price) %></div>
</div>
<% end %>

Any insight well appreciated

Was it helpful?

Solution

You've got a form_for @cart and you're trying to update an attribute on a line_item.

Change it to form_for line_item, get rid of your hidden field, and add @line_item.update_attributes(params[:line_item]) to LineItemController#update and it will work so long as line_items are defined as a resource.

That's the easiest way. The best way may be to use accepts_nested_attributes_for :line_items in your Cart model and use fields_for in your form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top