Ruby on rails 遍历JSON.Parse()会生成rails
我是一个rails新手,但我很喜欢它……无论如何,我遇到了一个问题,似乎找不到我要找的东西,因为大多数问题都是关于ActiveRecord对象的,等等,而我实际上使用的是rest Web服务中的JSON.parse 在我的表(视图中)中,如果没有错误或空行,我无法遍历对象。我知道我在视图中的代码是错误的,但是我已经尝试了很多我读过的不同的东西 我应该在视图中执行什么操作,或者在发送到视图之前是否需要转换为其他数据类型?如果你能给我任何帮助,我将不胜感激 谢谢 控制器代码:Ruby on rails 遍历JSON.Parse()会生成rails,ruby-on-rails,json,ruby,Ruby On Rails,Json,Ruby,我是一个rails新手,但我很喜欢它……无论如何,我遇到了一个问题,似乎找不到我要找的东西,因为大多数问题都是关于ActiveRecord对象的,等等,而我实际上使用的是rest Web服务中的JSON.parse 在我的表(视图中)中,如果没有错误或空行,我无法遍历对象。我知道我在视图中的代码是错误的,但是我已经尝试了很多我读过的不同的东西 我应该在视图中执行什么操作,或者在发送到视图之前是否需要转换为其他数据类型?如果你能给我任何帮助,我将不胜感激 谢谢 控制器代码: class Widge
class WidgetController < ApplicationController
def index
widget = Widget.new
@widgets = widget.fetchAll
end
end
class WidgetController
型号代码:
class Widget < ActiveRecord::Base
# class Widget
require 'net/http'
require 'json'
def fetchAll
uri = URI.parse("https://example.com/widgets")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
return JSON.parse(response.body)
end
end
class小部件
查看代码:
<% @widgets.each do |widget| -%>
<tr>
<td><%= puts "#{widget['id']}" %></td>
<td><%= widget[:name] %></td>
<td><%= widget.description %></td>
</tr>
<% end -%>
那个url“https://example.com/widgets“
返回包含错误的响应。在rails中,响应对象如下所示:
#<Net::HTTPNotFound 404 Not Found readbody=true>
...
...
response = http.request(request)
puts "*" * 20
p response
puts "-" * 20
然后查看启动服务器的窗口:
...
...
Started GET "/users/index" for 127.0.0.1 at 2017-02-18 20:57:16 -0700
Processing by UsersController#index as HTML
********************
#<Net::HTTPNotFound 404 Not Found readbody=true>
--------------------
...
...
(-v
代表verbose,它将发送的头与请求一起输出,也将接收的头与响应一起输出。如果没有-v选项,输出中将忽略头。)
右边的
是请求的文本。面向左侧的JSON是什么样子的?它是一个数组吗?详细的布局?谢谢富兰克林,我真的弄明白了:
成功了,我意识到它是在控制台上打印出来的,我发誓我试过了!是的,我猜你有PHP背景。在Rails中,put
In模板将其打印在服务器日志中,而不是网页上。此外,Rails是一个成熟的网络动物。因此,您不需要json或net/http——这已经为您做了。只是一个小提示:您不需要编写“#{widget['id']}”
,只需widget['id']
即可。
~$ curl -v "https://example.com/widgets"
* Trying 93.184.216.34...
* Connected to example.com (93.184.216.34) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: www.example.org
* Server certificate: DigiCert SHA2 High Assurance Server CA
* Server certificate: DigiCert High Assurance EV Root CA
> GET /widgets HTTP/1.1
> Host: example.com
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Cache-Control: max-age=604800
< Content-Type: text/html
< Date: Sun, 19 Feb 2017 03:59:57 GMT
< Expires: Sun, 26 Feb 2017 03:59:57 GMT
< Last-Modified: Mon, 13 Feb 2017
...
...