0

I have a table that displays all of a users Teacher models. I want the rightmost column of the table to contain 'edit' buttons that cause a bootstrap modal to appear with a form that submits to that models edit path.

So far I have a table with buttons whose id's correspond to the id's of the model they are displaying. When the buttons are clicked, the modal appears, but the form always submits to the same url. I'm having trouble finding a way to change the url that the form submits to based on the id of the button that was pressed.

Button:

<a id="edit-#{teacher_id_here}" href="#myModal" role="button" class="btn" data-toggle="modal">
  Launch demo modal
</a>

Modal:

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" 
     aria-labelledby="myModalLabel" aria-hidden="true">
    ... 
</div>
4

1 回答 1

0

一种可能性是在您的锚标记中使用自定义data属性(例如data-teacher_id),然后teacher_id通过绑定到锚标记的单击事件的回调来检索 。回调的功能是使用提取的更新模式中的表单teacher_id(请参阅jQuery.data()上的文档)

但是,在我自己的代码中,我使用了不同的方法。我会将锚标记转换为“ajaxified”链接,并#myModal用 TeacherController 的编辑操作返回的表单部分填充。在这种情况下,您的myModal部门最初将是空的。

该链接设置为指向正确的 URL 并由 Ajax 处理:

= link_to "Launch modal", edit_teacher_path(@teacher), :class => "btn ajax-modal-trigger", 
  :data => {:remote => true, :type => 'html'}

由于链接的data-remote属性设置为 true,Rails 会自动通过 ajax 将其提交到正确的 URL(即edit_teacher_path(@teacher). 现在你只需要绑定 ajax 成功事件就可以真正用表单填充模态并触发模态显示:

 $("body").on('ajax:success', "a.ajax-modal-trigger", function(evt, data, status, xhr){
   $("#myModal").html(data).modal('show');
 });

当然,在 TeachersController 的edit操作中,您需要确保处理 Ajax 请求并以正确的形式部分响应(请注意,html即使它是 Ajax 请求,格式也是如此。那是因为您要呈现 html 部分):

class TeachersContoller
  .....

  def edit
    @teacher = Teacher.find(parame[:id])
    respond_to do |format|
       format.html do
         render :partial => "form", :object => @teacher
       end 
     end
  end
end

每当您想要呈现动态模态时,您都可以将其用作通用方法。唯一需要更改的是锚标记指向的 url。

于 2013-05-11T19:24:07.037 回答