我有一个拥有_many line_items 的购物车模型。我正在尝试更新购物车中 line_item 对象的数量属性,但它似乎没有更新。我希望数量更新并重定向回同一页面。下面是我的代码,当我提交表单时,它只是重定向到数量值不变的同一页面
楷模
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
控制器
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
路线
get 'cart' => 'carts#show', :as => 'current_cart'
购物车/表演
<% 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 %>
任何见解都值得赞赏