In my Rails app I have key_contacts where you can add phone_numbers via a modal. The key_contacts are displayed on both Company show page and Sales_Opportunity show page in a table. When a user adds a new phone number for the key_contact, I'm using Jquery to reload the table so the newly added phone_number is now shown.
This worked fine until I wanted to do it across two different pages, because the key_contacts on the sales_opportunity show page are only those associated with that sales_opportunity, whereas those on the company show page are all contacts belonging_to the company.
Unless a sales_opportunity exists, the code breaks when adding a phone_number to a key_contact in the company view because there is no sales_opportunity object, and therefore there is no way to render the @sales_opportunity.key_contact. The solution to this would be to have create.js.erb understand which page it's being called from, and then only render the table relevant to that view.
My create.js.erb file:
//update the key contact table with the new phone number, and close the modal
$('#phone_number_modal').modal('hide')
.clear_previous_errors();
resetForm($('#new_phone_number'));
$input = $('#phone_number_error');
$input.closest('.form-group').removeClass('has-error').find('.warning-block').html('');
//render the newly added key contact to the table if the AJAX call succeeded
if (window.location.href.indexOf("companies") > -1) {
$('#key-contacts-table-div').html("<%= escape_javascript(render :partial => 'shared/key_contacts_table')%>");
}
if (window.location.href.indexOf("sales_opportunities") > -1) {
$('#key-contacts-table-div-2').html("<%= escape_javascript(render :partial => 'sales_opportunities/key_contacts_table')%>");
}
$('.alert').remove();
$('#key-contacts').DataTable({
retrieve: true,
});
This doesn't work - in spite of being on the companies route, the create.js.erb file STILL renders the sales_opportunities/key_contacts_table into the view, and still returns a 500 error because the Company does not yet have a sales_opportunity.
As an aside, if I comment out the line:
//$('#key-contacts-table-div-2').html("<%= escape_javascript(render :partial => 'sales_opportunities/key_contacts_table')%>");
It also still runs that code for some reason. I have to physically delete that line of code for the jquery to run correctly.
I know my create.js.erb is not an elegant piece of jquery, but I need this to work. Can anyone help me fix it please?
Aucun commentaire:
Enregistrer un commentaire