我是Ruby on Rails和编程的新手.到目前为止,我已成功使用我的控制台从API返回JSON数据,但我似乎无法使其在我的本地服务器上运行.
在我输入的控制台中:
httparty "http://rubygems.org/api/v1/versions/httparty.json"
在我设法安装/配置所有内容后它返回了JSON.
那么在控制台我写道:
rails new Catalog rails generate controller new index
当我去的时候,我按照教程在我的页面上显示:Hello, Rails!
http://localhost:3000/
现在我正在尝试返回JSON数据,并在同一页面上显示"Hello,Rails".
在index.html.erb我有:
Hello, Rails
<%= @result %>
在home_controller.rb我有:
class HomeController < ApplicationController def get_catalog include HTTParty @result = HTTParty.get("http://rubygems.org/api/v1/versions/httparty.json") end end
在routes.rb我有:
Catalog::Application.routes.draw do get "home/index" root :to => 'home#index' end
当我转到页面时,"Hello,Rails"下没有任何内容.
我仍然试图围绕所有这些东西如何相互作用.也许有人能看到我在这里做错了吗?
---更新我正在尝试将产品名称输出到li元素中.我的文件现在是:
index.html.erb:
控制器:
class HomeController < ApplicationController def index @response = HTTParty.get("myURL") @http_party_json = JSON.parse(@response.body) end end
我得到的错误是:
undefined method `[]' for nil:NilClass Extracted source (around line #5): 2:
当我取消['Name']时,我从JSON开始:
[{"Name"=>"3x4 Vinyl Magnet", "Description"=>"Made of durable high-gloss vinyl. Measures 3x4 inches and has rounded corners. Waterproof and scratch resistant."
为什么我不能以['Name']为目标来获得产品名称?