我和这个人遇到了同样的问题
我和他一样把 rjs 改成 js.erb。而且我们都使用<%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>
向控制器发送 AJAX 请求。format.js
罚款并执行create.js.erb。但是购物车没有添加任何东西。
日志结果:
Rendered line_items/_line_item.html.erb (4.3ms)
Rendered carts/_cart.html.erb (8.0ms)
Rendered line_items/create.js.erb (8.8ms)
那就是我们发送 AJAX 请求的 index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% @products.each do |product| %>
<div class="entry">
<%= link_to image_tag(product.image_url), line_items_path(:product_id => product), html_options = {:method => :post} %>
<h3><%= product.title %></h3>
<%=sanitize product.description %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price,:precision=>3) %></span>
<%= button_to 'Add to Cart',line_items_path(:product_id => product) ,:remote=>true %>
</div>
</div>
<% end %>
那就是处理请求的 line_items 控制器函数
# POST /line_items
# POST /line_items.json
def create
# for exercise only
session[:counter] = nil
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to store_index_path }
format.js
format.json { render json: @line_item, status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
创建.js.erb
$('#cart').html("<%= escape_javascript(render(@cart)) %>");