How can I refresh a datatable on rails after an up

2019-09-01 07:10发布

问题:

I'm a Rails newbie and I have a full working datatable (thanks to railscasts #340).

In my datatable view I set up 2 buttons:

<button id="Refresh" type="button">Refresh</button>
<td><%= button_to 'dogroup', dogroup_utyord_path(format: "json"), remote: true %></td>

<table id="utyords" class="display" data-source="<%= utyords_url(format: "json") %>" width="100%">
...
</table>

Here is my working coffescript:

jQuery ->
  oUtyordTable = $('#utyords').dataTable
  sPaginationType: "full_numbers"
  bJQueryUI: true
  bProcessing: true
  bServerSide: true
  sAjaxSource: $('#utyords').data('source')

$("#Refresh").click ->
  oUtyordTable.fnDraw()

in my controller:

def index
  @utyords = Utyord.all
  respond_to do |format|
    format.html 
    format.json { render json: UtyordsDatatable.new(view_context) }
  end
end

def dogroup
  ddett = Utyord.all
  ddett.update_all "grp = 1"
  respond_to do |format|
    format.html 
    format.json 
  end
end

I push the "dogroup" button and the action updates records on the database correctly: when I push the "refresh" button I can see the datatable updated.

Everything works fine, but.... is there a way the datatable updates when I push the "dogroup" button without have to push the "refresh" button?

I know I miss something...

回答1:

Could something as simple as this work?

$('input[value="dogroup"]').mouseup ->
    oUtyordTable.fnDraw()

Try it... Mouseup because we want it to run after click.

If it doesn't, then add an identifier to the form:

<%= button_to 'dogroup', dogroup_utyord_path(format: "json"), 
                         remote: true, form_class: "dogroup_form" %>

And then submit the form and after than run a script:

$(".dogroup_form").submit(e)->
     e.preventDefault()         #to stop the form
     $(this).submit()           #to manually submit it and
     oUtyordTable.fnDraw()      #to run your function

UPDATE: From this post: to use a response from a form's ajax request that has not been handled by your own code, you can bind an event to your form (in plain javascript, not coffeescript):

Discard my proposed $(".dogroup_form").submit(e)-> functionality and add this:

$(".dogroup_form").bind('ajax:complete', function() {
    oUtyordTable.fnDraw();
});

From online, this could be the CoffeeScript equivalent to the above:

$(".dogroup_form").bind "ajax:complete", ->
    oUtyordTable.fnDraw()
    return