Ruby Rails-在循环中呈现Ajax
我想用ajax更新视图中的几个单个表单元。 在循环过程中是否有可能多次运行正常运行时间部分? 目前,循环会迭代所有给定的记录,但部分记录只运行一次Ruby Rails-在循环中呈现Ajax,ruby,foreach,ruby-on-rails-5,Ruby,Foreach,Ruby On Rails 5,我想用ajax更新视图中的几个单个表单元。 在循环过程中是否有可能多次运行正常运行时间部分? 目前,循环会迭代所有给定的记录,但部分记录只运行一次 def CheckUptimes require 'net/ssh' @username = "updater" @password = "üqwlp+ß$2" @cmd = "uptime" @items = Item.all.where("(category = 'Ubuntu 14 LTS')") @items.each
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
如果我理解得很好,我认为您可以在两个实例变量(数组)中保存哪些主机名可以连接,哪些不可以,然后在
checkuptimes.js.erb
中显示哪些可以连接
像这样的
@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
在本例中,部分
正常运行时间
的渲染次数与包含@con_ok的项的渲染次数相同,使用局部变量con_ok
,数组中的项(id)似乎不允许多次渲染:-(AbstractController::DoubleRenderError)(此操作中多次调用了Render和/或redirect。请注意,您只能调用Render或redirect,每个操作最多只能调用一次。还请注意,redirect和Render都不会终止操作的执行,因此,如果您想在重定向后退出操作,则需要执行类似“redirect_to(…)并返回”的操作。):js.erb中是否存在此错误?可能需要渲染部分“正常运行时间”
而不是渲染“正常运行时间”…
$("#mydiv").html("<%= escape_javascript(render 'uptime', collection: @con_ok)%>");