我想创建一个ruby应用来检查服务器状态是上升还是下降。 稍后我会找到一种方法来调整我的json路径,以便在多种语法中找到一种方法。但是现在,我仍然坚持使用一个脏的“未定义的方法`每个'为nil:NilClass”
Ping控制器:
def index
@pings = Ping.all
end
def new
@service = Ping.new
end
def create
@ping = Ping.new(ping_params)
@ping.service = @service
@ping.up = test_ping
@ping.save
end
def test_ping
require 'json'
require 'open-uri'
url = 'https://www.facebook.com/platform/api-status/'
fb_status_serialized = open(url).read
fb_status = JSON.parse(fb_status_serialized)
if fb_status['current']['health'] == 1
test_ping = true
else
test_ping = false
end
end
private
def ping_params
params.require(:ping).permit(:service_id, :up)
end
def set_ping
@ping = Ping.find(params[:ping_id])
end
end
服务控制器:
(这是我想要添加的服务的设置)
class ServiceController < ApplicationController
before_action :set_service, only: [:edit, :show, :destroy]
def index
@services = Service.all
end
def new
@service = Service.new
end
def edit
end
def show
end
def create
@service = Service.new(service_params)
@service.save
if @service.save
redirect_to service_path(@service)
else
render :new
end
end
def destroy
@service.destroy
@service.destroy
redirect_to services_path
end
private
def set_service
@service = Service.find(params[:id])
end
def service_params
params.require(:service).permit(:name, :web_api, :json_path)
end
end
查看(服务索引):
<%= @services.each do | s | %>
<p><%= s.name %></p>
<p><%= s.web_api %></p>
<p><%= s.json_path %></p>
<p><%= s.id %></p>
<%= @pings.each do | p | %>
<%# if p.service_id == s.id %>
<!-- undefined -->
<% end %>
<p>|||</p> <%= Ping.new(up: true, service: s ) %> <p>|||</p>
<% end %>
答案 0 :(得分:2)
您尝试迭代@pings
迭代内的@services
,但尚未定义,您只定义了服务和迭代如果正在应用each
的对象具有nil
值,则ping不会起作用。
无论您使用什么控制器来渲染视图,都需要定义两个实例变量,请尝试:
def index
@services = Service.all
@pings = Ping.all
end