Reputation: 4610
I have an ajax post to my backend rails app, it's to post a upload a file.
Post response with my files list in JSON
After that I need to reload my files list at view detalhes.html.erb page. This list is a partial. Here is what I have:
controller method:
def upload_arquivo
@ponto_venda = PontoVenda.find(params[:pv_id])
nome = params[:key].split('/').last
@arquivo = Arquivo.new(nome: nome, endereco: params[:url], s3_key: params[:key], tamanho: params[:tam], user_id: params[:u_id], tag_id: params[:tag])
if @arquivo.save!
ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
response = { files: filtro_pv_arquivos, message: "O arquivo '#{nome}' foi salvo" }
else
response = { files: '', message: 'Ocorreu um erro ao salvar o arquivo, por favor, tente novamente' }
end
render json: response
end
My ajax post method at _arquivos_upload.html.erb
:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
console.log(data.files.length);
// trying to reload partial after post request
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados") %>");
});
data.files are correct, I just need to find a way to pass this to my render partial. How can I do that? Or if this is a bad way to do it, how can I do better?
Here is where I render my partial detalhes.html.erb
:
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados" %>
</div>
I already have try a lot of this:
Upvotes: 1
Views: 1284
Reputation: 20253
I think I would render back html
instead of json
. Then, in .success
function of the ajax
call, just do:
$.ajax({
url: 'some_url,
type: 'post', processData: false
})
.success(function(data) {
$('#display-arquivos').html(data);
});
You'll probably need to change your controller action along the lines of:
def upload_arquivo
...
if @arquivo.save!
ArquivoPontoVenda.create(arquivo_id: @arquivo.id, ponto_venda_id: @ponto_venda.id, fachada: false)
@files = #populate your @files variable
render "arquivos_buscados"
else
render :something_else
end
end
Upvotes: 1
Reputation: 787
That looks good. I'd suggest modifying your partial to accept a local variable and then explicitly passing it in when you render the partial.
<div class="card" id="display-arquivos">
<%= render "arquivos_buscados", locals { files: @files #add this } %>
</div>
$('#display-arquivos').html("<%= escape_javascript(render "arquivos_buscados", locals: { files : data.files } ) %>");
Upvotes: 1