[英]Shopping Cart modal when adding a new item - rails 5 jquery
我希望購物車在用戶向其中添加商品時顯示為模式。 “添加到購物車”按鈕位於 products#show 視圖頁面上,在一個 form_tag 內,該標簽發布到 order_items#create controller 以便在購物車中創建新項目。 我很困惑,因為我想要的是購物車的展示,但我想我不想調用我的購物車 controller,只需從 order_item 創建操作中調用它的視圖。 我在我的views/order_items 文件夾中添加了一個create.js.erb,並在布局文件夾中添加了一個部分。 我得到的是這個錯誤: ActionController::UnknownFormat (OrderItemsController#create 缺少此請求格式和變體的模板。我不知道如何讓 rails 找到正確的模板。有人可以幫忙嗎?
產品#show
<%= form_tag order_items_path class: "coffee_form", remote: true do %>
<%= select_tag "grind", raw("#{raw_str}"), multiple: false, class:"coffee_form btn-block form-control-lg" %>
<%= label_tag Product.human_attribute_name("weight")%>
<%= select_tag "weight", raw("<option>250</option><option>1000</option>"), multiple: false, class:"coffee_form btn-block form-control-lg", id:"selected_weight", onchange: "displayPrice();" %>
<%= hidden_field_tag 'product_id', @product.id %>
<div class='mt-3'>
<%= submit_tag t("addcart"), class: 'btn btn-block btn-warning', data: { toggle: 'modal', target: '#myModal'} %>
訂單項#create
def create
chosen_weight = params[:weight].to_i
chosen_product = Product.find(params[:product_id])
....
@order_item = OrderItem.new
....
if session[:cart_id] == nil
@current_cart = Cart.create
session[:cart_id] = @current_cart.id
end
@order_item.cart_id = @current_cart.id
@order_item.product = @product
@order_item.grind = params[:grind]
@order_item.quantity = params[:quantity]
@order_item.shipping_points = @product.shipping_points * params[:quantity].to_i
@order_item.save!
respond_to do |format|
format.html # create.html.erb
format.js # create.js.erb
end
在 views/order_items 文件夾中創建.js.erb
$('myModal').html('<%= j render "layouts/modal"');
_modal.html.erb 在視圖/布局文件夾中
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
您可能希望從order_items#create
操作重定向到carts#show
,但請確保您在沒有布局的情況下進行渲染。
然后,當您使用fetch
發布新的訂單商品時,獲取呈現的內容並將其放入您的 modal/popover/other.xml 中。
如果您使用 turbo,您可以通過在 turbo 框架中渲染模態來使其自動發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.