0

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

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Seems that multiple rendering is not allowed :-( AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".):
Is this error in js.erb? May need render partial ‘uptime’ instead of render ‘uptime’...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.