У меня этот код в файле store.html.erb
<%= link_to t('.add_html'), 'javascript:void(0);',
:class => "line-item", :product => product.id %>
<script type="text/javascript">
$('document').ready(function(){
$(".line-item").click(function(){
var prod = $(this).attr('product');
$.ajax({
url:'<%= line_items_url %>',
data: {product_id: prod},
type: 'POST',
dataType: 'script'
});
});
});
</script>
my line_items_controller.rb имеет этот код
def create
@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_url) }
format.js { @current_item = @line_item }
format.xml { render :xml => @line_item,
:status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
И тогда мой файл create.js.erb имеет этот код
$("#notice").hide()
$("#cart").html("<%= j render(@cart) %>")
И мой _cart.html.erb
<% unless cart.line_items.empty? %>
<div class="cart_title"><%= t('.title') %></div>
<table>
<%= render(cart.line_items) %>
<tr class="total_line">
<td colspan="2">Total</td>
<td class="total_cell"><%= number_to_currency(cart.total_price) %> </td>
</tr>
</table>
<%= button_to t('.checkout'), new_order_path, :method => :get %>
<%= button_to t('.empty'), cart, :method => :delete,
:confirm => "Are you sure?" %>
<% end %>
Теперь, когда я нажимаю кнопку "Добавить в корзину", продукты должны добавляться в корзину, и это должно показывать обновленное значение в левой части страницы, но оно не показывает это. Но когда я обновляю страницу, я вижу обновленное значение. Это означает, что мой javascript не работает. Пожалуйста, дайте мне знать, почему мой javascript не работает.
Добавьте эту строку в файл create.js.erb
$("#cart").html("<%= escape_javascript(render(@cart)) %>");
Это должно работать
вы должны отправить @cart
как locals в частичной части корзины и вызывающе, он будет динамически обновлять значение.