Stef Hej
Stef Hej

Reputation: 1377

Rails - Render Ajax inside a loop

I'd like to update several single table cell in my view with ajax. Is there a chance to run the uptime partial several times during the loop? Currently the loop iterates over all given records but the partial runs once.

def CheckUptimes
  require 'net/ssh'
  @username = "updater"
  @password = "üqwlp+ß$2"
  @cmd = "uptime"
  @items = Item.all.where("(category = 'Ubuntu 14 LTS')")
  @items.each do |ci|
    @hostname = ci.name
    begin
      ssh = Net::SSH.start(@hostname, @username, :password => @password)
      @uptime = ssh.exec!(@cmd)
      ssh.close
      @uptime = @uptime.strip
      ci.update_attributes(:uptime => @uptime)
      respond_to do |format|
        format.html
        format.js { render :partial => "uptime", :locals => { :id => ci.id, :uptime => @uptime } }
      end
    rescue
      puts "Unable to connect to #{@hostname} using #{@username}/#{@password}"
    end
  end
end

Upvotes: 0

Views: 179

Answers (1)

Albert Català
Albert Català

Reputation: 2044

If I understand well, I think you could save in two instance variables (Arrays) which hostnames were able to to connect and which not, and then in checkuptimes.js.erb you can show which ones are ok with render collection

Something like this

@con_ok=@con_ko=[]
@items.each do |ci|
@hostname = ci.name
begin
  ssh = Net::SSH.start(@hostname, @username, :password => @password)
  @uptime = ssh.exec!(@cmd)
  ssh.close
  @uptime = @uptime.strip
  ci.update_attributes(:uptime => @uptime)
  con_ok<<ci.id
rescue
   con_ko<< ci.id
end
respond_to do |format|   ## Not necessary ##
   format.html
   format.js
end

in checkuptimes.js.erb

$("#mydiv").html("<%= escape_javascript(render 'uptime', collection: @con_ok)%>");

in this example, the partial uptime will be rendered as many times as items contains @con_ok, with a local variable con_ok with the the item in the array (id)

Upvotes: 1

Related Questions