【发布时间】:2016-01-23 20:50:45
【问题描述】:
如何将变量传递给视图之外的模型?问题是,我不得不将模型移动到application.html.erb,因为z-index conflicts 在products/index.html.erb 视图中有模态代码。
例如,我想将<%= product.id %> 变量传递给模式弹出窗口。
产品/index.html.erb
<% products.each do |product| %>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#productDetails" productId="<%= product.id %>">
Launch <%= product.id %>
</button>
<% end %>
布局/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<%= stylesheet_link_tag 'application' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="page-wrapper">
<%= render 'layouts/header' %>
<%= yield %>
<%= render 'layouts/footer' %>
</div>
<!-- Modal -->
<div class="modal fade" id="productDetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body product-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
</html>
尝试
我尝试添加 javascript 来传递变量,但没有任何显示:
<script>
$('#productDetails').on('show.bs.modal', function(e) {
var $modal = $(this),
productId = e.relatedTarget.productId;
$.ajax({
cache: false,
type: 'POST',
url: 'backend.php',
data: 'EID=' + productId,
success: function(data) {
$modal.find('.product-content').html(productId);
}
});
})
</script>
我也尝试在 products/index.html 中添加部分,但由于 z-index 冲突,无法从 products/index.html.erb 中调用模态。
【问题讨论】:
-
这真的没有意义,您的索引视图将显示许多产品 - 您究竟想将哪一个传递给您的模态,为什么要将其发布到 PHP 脚本?我会退后一步,因为这听起来像 X and Y problem。
-
@max 抱歉,该按钮实际上嵌套在产品的 for 循环中,我已经更新了
products/index.html.erb的代码 -
@Onichan 看看这是否有帮助 jsfiddle.net/9pkbnanz/1
-
@Shehary 谢谢。它看起来像它的工作,但我怎样才能将产品 ID 传递到模态中的
link_to按钮?<%= link_to add_to_cart_path(:product_id => product.id), :method=> :post do %> -
@Onichan,对不起,我对 ruby 不熟悉,所以无法给你一个提示
标签: ruby-on-rails ruby twitter-bootstrap