使用在帮助程序中使用的link_to模式传递Rails变量

时间:2016-03-22 18:00:48

标签: javascript ruby-on-rails twitter-bootstrap bootstrap-modal

我无法理解如何将变量传递给模态,因此我可以使用(不是作为表单中的输入)而是在辅助方法中使用。

我已查看过:DEMO 2Passing data to a bootstrap modal以及How to pass values arguments to modal.show() function in Bootstrap

Link_to模式:

<%= link_to "#{comment.fname}", "#commenterModal", :class => "btn commenter", "data-toggle" => "modal", "data-id" => "4"%>

我正在使用data-id =&#34; 4&#34;测试,但我将传递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)传递给模态,这样我就可以在调用帮助器方法时使用它&#34; getuserprofileofcommenter(commentId)& #34 ;.

任何见解都会有所帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

据我了解,您希望每次单击评论链接时更改模态的内容。

在这种情况下,我通常会使用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');

此代码未经过测试。

希望它有所帮助。

答案 1 :(得分:0)

如您所述,这是不可能的。服务器响应后JS正在运行,因此在此期间无法调用任何rails助手。 (rails helper仅在呈现视图时在服务器端运行)

实现所需内容的方法是在单击链接时对服务器执行ajax请求,并在js响应中,您将具有必要状态(由控制器提供)以与已打开的模式进行交互