我到处都找过了,但似乎找不到为什么我的Ajax请求没有被用于向Cart中添加条目的问题。
line_items_controller.rb
def create
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_url }
format.js { @current_item = @line_item }
format.json { render action: 'show',
status: :created, location: @line_item }
else
format.html { render action: 'new' }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
end
store/index.html.erb
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Your Pragmatic Catalog</h1>
<% cache ['store', Product.latest] do %>
<% @products.each do |product| %>
<% cache ['entry', product] do %>
<div class="entry">
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line">
<span class="price"><%= number_to_currency(product.price) %></span>
<%= button_to 'Add to Cart', line_items_path(product_id: product),
remote: true %>
</div>
</div>
<% end %>
<% end %>
<% end %>
line_items/create.js.erb
$('#cart').html("<%= escape_javascript render(@cart) %>");
$('#current_item').css({'background-color':'#88ff88'}).
animate({'background-color':'#114411'}, 1000);
line_items/_line_item.html.erb
<% if line_item == @current_item %>
<tr id="current_item">
<% else %>
<tr>
<% end %>
<td> <%= line_item.quantity %>× </td>
<td> <%= line_item.product.title %> </td>
<td class= "item_price" > <%= number_to_currency(line_item.total_price) %> </td>
</tr>
可以在日志文件中看到,每当我向购物车Cart添加一个项目时,页面就会发送一堆GET请求,而且我还可以看到它重新加载,但日志文件中没有发现错误。我多次重新启动该网站,并检查是否正确安装了jQuery和jQuery-UI gems,但什么作用都没有。