CRUD model in a bootstrap modal with jquery, ajax - best practice

Hi,

i have an model, which i want to show edit and update in a dialog via ajax.

What i do at the moment:

To open the Modal and render the partial, i send an ajax request to controller#show with ujs

this is the link:

Fidel Markus Armstrong

this runs the script in new.js.erb which renders the show partial inside the dialog and opens it.

To get the edit form, i do the same

Fidel Markus Armstrong

this runs edit.js.erb

Now: To update my model, i send the form data as json to the controller#update

if there is an error in the form, i do render_to_string(form_partial) inside the controller and respond with this inside of the json response.

Now i have the partial html inside of the json object. I do this, to get the rails error messages and fields_with_errors.

Is there a better way to do it? all the mix between script and json format and the partial html inside the json doesn’t feel right.

This is the ajax for the form submit:

$(‘#dialog’).on(‘submit’, →

$(this).find(‘form’).unbind(‘ajax:beforeSend’).bind(‘ajax:beforeSend’,(evt, xhr, settings) →

).unbind(‘ajax:success’).bind(‘ajax:success’,(evt, data, status, xhr) →

#insert Data to selectbox it there comes a type attribute with the request

if xhr.status == 201 # :created

url = data.url #this is en/people/:id

Load show dialog on success - runs show.js.erb

$.ajax({

url: url,

type: ‘get’,

dataType: ‘script’

})

else

Render the dialog html including the error messages and fields with errors

$(‘#person-dialog’).html(data.error) #data.error is the partial

$(‘.field_with_errors input’).first().trigger(‘focus’)

$(‘.modal-header’).prepend(action)

false

).unbind(‘ajax:complete’).bind(‘ajax:complete’,(evt, xhr, settings) →

).unbind(‘ajax:error’).bind(‘ajax:error’, (evt, xhr, status, error) →

)

)