我很难理解如何将变量传递给模态,以便我可以使用(不是作为表单中的输入),而是在辅助方法中使用。
我看过:将数据传递到引导模式和如何将值参数传递给 Bootstrap 和 Bootstrap JavaScript 中的 modal.show() 函数
Link_to模式:
<%= link_to "#{comment.fname}", "#commenterModal", :class => "btn commenter", "data-toggle" => "modal", "data-id" => "4"%>
我正在使用 data-id="4" 进行测试,但我会在 Rails 变量 comment.id 传递。
模 态:
<div id="commenterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body" style="background-color: #F5F5F5;">
<div class="row" id="commentId">
<%= getuserprofileofcommenter(commentId).bio %>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>
</div>
</div>
</div>
</div>
</div>
.JS:
$(document).ready(function() {
$('#commenterModal').on('show.bs.modal', function(event) {
$("#commentId").val($(event.relatedTarget).data('id'));
});
});
我知道我没有正确理解这一点。但是当我单击link_to时,我正在尝试使用此实例,将变量 (comment.id) 传递给模态,以便在调用辅助方法"getuserprofileofcommenter(commentId)"时可以使用它。
任何见解都会有所帮助。谢谢!
据我了解,您希望每次单击评论链接时都更改模态的内容。
在这种情况下,我通常会帮助 rails ajax。
将模态内容提取到部分_show_modal.html.erb
<div id="commenterModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body" id="commentUserModal">
<%= getuserprofileofcommenter(@comment.id).bio if @comment.present? %>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>
</div>
</div> <!-- modal-content -->
</div> <!-- modal-dialog -->
</div> <!-- modal -->
模板包含link_to
:
<%= link_to comment.fname, show_modal_groups_path(comment_id: comment.id), :class => "btn", remote: true %>
<!-- rendering partial -->
<div id="commentUserModal">
<%= render 'show_modal' %>
</div>
comments_controller.rb
def show_modal
@comment = Comment.find_by_id(params[:comment_id])
respond_to do |format|
format.js {render 'show_modal'}
end
end
评论/show_modal.js.erb
$("#commentUserModal").html("<%= j render 'show_modal' %>");
$("#commenterModal").modal('show');
未测试此代码。
希望对您有所帮助。
这不可能像你描述的那样。 JS在服务器响应后运行,因此在此期间无法调用任何rails帮助程序。 (Rails 帮助程序仅在渲染视图时在服务器端运行)
完成您想要的方法是在单击链接时向服务器执行 ajax 请求,并且在您的 js 响应中,您将拥有与已经打开的模式交互的必要状态(由控制器提供)