Question

I have a simple app that is using Ajax with a modal to add and update records in a regular table view.

I have adding new records working by just appending the new table row/record to the bottom of the table, but am having trouble figuring out how to show the changes after updating an existing record. Here is some code:

update.js.erb

  console.log('Updated');
  $('#dialog-form').dialog('close');
  $('#dialog-form').remove();
  $('table').update record somehow?

Normally I would do something like

$(this).closest('tr').remove();
$(this).closest('tr').append('whatever');

but this won't work because the update button is in a modal, and not in the actual table.

For reference, here is how I add a new record:

create.js.erb

  console.log('Created');
  $('#dialog-form').dialog('close');
  $('#dialog-form').remove();
  $('table').append('<%= escape_javascript(render(@exercise)) %>');
  $('tr').last('tr').effect('highlight');
Was it helpful?

Solution

You can do it like this:

# index.html.erb
<table>
  <tbody>
    <% @exercises.each do |exercise| %>
      <tr id="exercise_<%= exercise.id %>">
        <td><%= exercise.name %></td>
        # etc...
      </tr>
    <% end %>
  </tbody>
</table>

# update action in controller:
def update
  @exercise = Exercise.where(id: params[:id]).first
  @exercise.update_attributes(params[:whatever])
  # etc ...

# update.js.erb
console.log('Updated');
$('#dialog-form').dialog('close');
$('#dialog-form').remove();
$('table tr#exercise_<%= @exercise.id %>').replaceWith('<%= escape_javascript(render(@exercise)) %>');

Hope this helps! Feel free to ask any question about this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top