如何使用内联:使用AJAX调用确认html助手的选项?

时间:2013-04-11 21:19:38

标签: ajax ruby-on-rails-3 ruby-on-rails-3.2 coffeescript

我正在尝试使用与按钮关联的记录删除的AJAX实现。问题是在这种情况下似乎没有触发 ajax:success 事件。

我已经实施了这篇文章的建议:Rails :confirm modifier callback?)但我不确定这是否是首选方式。

我想知道在这种情况下,社区智慧是否有帮助。什么是正确的方法?

应用程序/视图/比赛/ show.html.haml:

%td= button_to 'Delete', contender, remote: true, method: :delete, class: 'delete_contender', confirm: 'Are you sure?' if owns?

应用程序/资产/ Javascript角/ competitions.js:

$(document).ready(function() {
  $('.delete_contender').on('confirm:complete', function(e, res) {
    if (res) {
      $(e.currentTarget).closest('tr').fadeOut();
    }
  });
});

应用程序/控制器/ contenders_controller.rb:

def destroy
  @contender = Contender.find(params[:id])
  @competition = @contender.competition
  @contender.destroy

  respond_to do |format|
    format.js   
    format.html { redirect_to @competition, notice: "Contender #{@contender.sn_name} has been deleted" }
    format.json { head :no_content }
  end
end

1 个答案:

答案 0 :(得分:0)

快速回答是:这不是正确的方法。答案如下。

我不应该使用.delete_contender类作为动作绑定的锚,而应该使用“form [data-remote]”,因为* button_to * helper会生成一个表单。此外,没有必要将JS钩子保留在资产管道中,最好将其移动到视图并转换为CoffeeScript。 Rails 3风格的解决方案是:

应用程序/视图/比赛/ show.html.haml:

%td= button_to 'Delete', contender, remote: true, method: :delete, confirm: 'Are you sure?' if owns?

应用程序/视图/比赛/ destroy.js.coffee:

jQuery ->
  $("form[data-remote]").on "ajax:success", (e, data, status, xhr) ->
    $(e.currentTarget).closest('tr').fadeOut()

应用程序/控制器/ contenders_controller.rb:

respond_to :js, only: :destroy

def destroy
  @contender = Contender.find(params[:id])
  @competition = @contender.competition
  @contender.destroy
end