问题
I have a rails form that imports remotely some products from a google spreadsheet. While doing so, it updates company that makes those products by setting its company.import_status to "started", when the importing starts, and "finish", once it's done.
I have a page that shows company.import_status, and I try to update it so I can see when an import starts and when it's finished. My code looks like this:
$(document).ready(function(){
<% @companies.each do |company| %>
setInterval(function(company){
$.ajax({
type : 'GET',
url : 'import',
dataType : 'html',
success : function(company){
$("#company_<%=company.id%>").html("<%= escape_javascript(Company.where(id: company.id).first.import_status) %>");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
}
});
}, 1000);
<% end %>
});
For some reason, the field doesn't get updated. It starts off as "started" and just stays that way. What can I change to fix this? If I try getting it through console, it gives me the correct value.
Update:
this is my import method
def import
@companies = Company.find(params[:company].values.map{ |c| c[:id] }.compact)
@companies.each do |company| company.key = params[:company].values.select {|c| c[:id] == company.id.to_s}.first[:file] if !company.import_in_progress? company.import_start
end
end
respond_to do |format|
format.html { redirect_to admin_import_index_path }
format.js
end
end
回答1:
you need to reload the records to get latest updated ones..use reload.i Used it to get the confirmation_token
which was somehow giving me the old one...so i used it to get the latest data from the db..
User.find(current_user.id).reload
..HOPE IT HELPS
回答2:
What was happening is that ruby code got compiled and kind of hardcoded first, so when javascipt took place, whatever was initially set in ruby stayed that way. That-s why I kept getting "started". This is what approach I used instead:
$(document).ready(function(){
setInterval(function() {
$.get("/companies.json", function(data){
$.each(data, function(index, c) {
var field = "#company" + "_" + c["id"];
$(field).html(c["import_status"]);
console.log(field);
});
});
}, 5000);
});
来源:https://stackoverflow.com/questions/26583070/how-to-get-updated-value-from-a-database-and-show-it-on-the-page-using-ajax