0

I am trying to have an AJAX implementation of record deletion associated with a button. The problem is that ajax:success event doesn't seem to be triggered in such case.

I have implemented the suggestion from this post: Rails :confirm modifier callback?) but I am uncertain if it's the preferred way.

I was wondering if communal wisdom could help in this case. What's the right approach here?

app/views/competitions/show.html.haml:

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

app/assets/javascripts/competitions.js:

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

app/controllers/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
4

1 回答 1

0

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

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

app/views/competitions/show.html.haml:

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

app/views/competitions/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
于 2013-04-18T18:35:32.307 回答