I am updating a simple text_area in Rails using Ajax:
application.js:
$("#invoice_project_id").change(function() {
var value=$(this).val();
$.get('/invoices/get_recipient', {project_id= : value} function(response) {
$('#invoice_recipient').val(response);
})
});
get_recipient.js:
$('#invoice_recipient').val("<%= @recipient.to_s.gsub!(/\n/, '\n') %>");
invoices_controller.rb:
def get_recipient
project = Project.find(params[:project_id])
@recipient = project.person.address
end
The code works great and replaces the value of the recipient text_area with the correct address, depending on what project gets chosen in the select menu.
The problem is that it works only with the addresses that already exist in the database. (I am using the Rails Faker gem to populate my database.) The moment I re-save a person‘s address manually in my Safari browser, the text_area won’t get updated through Ajax anymore when I try to do so using the above code.
How is this possible?
I am already escaping the newline characters using the gsub! method above, so I can’t think of anything else I could do.
Can anybody help?
Thanks…
OK, turns out that the carriage returns in the addresses were causing the trouble.
These carriage returns are only created when updating an address in the browser through a
textarea. The Faker gem mentioned above creates newline characters but no carriage returns.I saw this only when inspecting my database records on the console because
\rand\ncharacters are invisible anywhere else I looked.So in my particular case I just needed to remove the carriage returns in my model like so:
I was not able to do this in any of my javascript files.
Just one simple line of code, but several hours of work for me. So hopefully somebody else will benefit from this.