我有产品和订单模型。产品有很多订单,订单属于产品。产品页面上有一个“订单”按钮,当用户点击它时,会打开一个引导模式。在这个模态上,我渲染订单的表单来创建一个新表单。
我想知道,如何在modal上将产品的ID传递给此表单? 目前我打开模态的按钮看起来像这样:
%button.btn.btn-info.btn-lg{"data-target" => "#myModal", "data-toggle" => "modal", :type => "button"} Order
模态本身:
#myModal.modal.fade{:role => "dialog"}
.modal-dialog
.modal-content
.modal-header
%button.close{"data-dismiss" => "modal", :type => "button"} ×
%h4.modal-title Order form
.modal-body
= render 'orders/form'
.modal-footer
%button.btn.btn-default{"data-dismiss" => "modal", :type => "button"} Close
我需要此产品的ID来创建一个属于该产品的新订单。如果我想错误的方向,请纠正我。
非常感谢您的帮助!
更新 已解决!! 感谢 Arup Rakshit (@ArupRakshit)!!!
- @products.last(3).each do |product|
%h4= product.name
%button.btn.btn-info.btn-lg{"data-target" => "#myModal", "data-toggle" => "modal", :type => "button", data: {product_id: product.id}} Order
#myModal.modal.fade{:role => "dialog"}
.modal-dialog
.modal-content
.modal-header
%button.close{"data-dismiss" => "modal", :type => "button"} ×
%h4.modal-title Order Form
.modal-body
#new_order
= render 'orders/form', product: product
.modal-footer
%button.btn.btn-default{"data-dismiss" => "modal", :type => "button"} Close
订单/形式:
= form_for Order.new do |f|
= f.hidden_field :product_id
= f.text_field :user_name, placeholder: 'Name', class: 'form-control'
= f.submit 'Order', class: 'btn btn-primary'
的application.js:
$( document ).ready(function() {
$('body').on('shown.bs.modal', '#myModal', function (e) {
var product_id = $(e.relatedTarget).data('product-id');
$('#order_product_id').val(product_id);
});
});
答案 0 :(得分:7)
使用数据属性将产品保留在模态按钮中。像
%button.btn.btn-info.btn-lg{"data-target" => "#myModal", "data-toggle" => "modal", :type => "button", data: {product_id: @product.id}} Order
在表单内添加隐藏字段:
= form_for Order.new do |f|
.form-group
= f.text_field :user_name, placeholder: 'Name', class: 'form-control'
= f.hidden_field :product_id
你需要在JS下面使用,填充隐藏的字段值。
$('body').on('shown.bs.modal', '#myModal', function (e) {
var product_id = $(e.relatedTarget).data('product-id');
$('#order_product_id').val(product_id);
});
#new_order
是ID
形式,将其更改为您的一个。 Bootstrap modal events。