TypeError - 没有将String隐式转换为Integer

时间:2017-06-28 15:32:29

标签: ruby-on-rails ruby rest

请原谅我的noob问题。

我在我的rails应用中使用https://newsapi.org/,我使用的是httparty gem。

def news
    @techcrunch = HTTParty.get('https://newsapi.org/v1/articles?source=techcrunch&apiKey=766c2f65e93c477451455xxxxxxxxxxx',
    :headers =>{'Content-Type' => 'application/json'} )
    respond_to :html, :json 
end   

news.html.erb

    <% if (@techcrunch.nil? or @techcrunch== []) %>
    <p> <h2>No news found.. Sorry</h2></p>
    <% else %>
      <% @techcrunch.each do |techcrunch| %>
          <td><%= link_to(image_tag(techcrunch["urlToImage"], height: '100', width: '100'), techcrunch.articles["url"])%></td>
          <td><%= link_to(techcrunch["title"], techcrunch["url"]) %></td>
          <td><%= techcrunch["publishedAt"] %></td>
      <% end %>
    <% end %>

我现在收到错误

  

没有将String隐式转换为整数

<td><%= link_to(image_tag(techcrunch["urlToImage"], height: '100', width: '100'), techcrunch.articles["url"])%></td>

我在postman中检查了API,响应如下

{
    "status": "ok",
    "source": "techcrunch",
    "sortBy": "top",
    "articles": [
        {
            "author": "Matthew Panzarino",
            "title": "Apple Music’s first new personalized playlist wants you to Chill",
            "description": "This week Apple is beginning to roll out the first new personalized playlist under Apple Music’s ‘For You’ section. The playlist, entitled ‘Chill’..",
            "url": "https://techcrunch.com/2017/06/27/apple-musics-first-new-personalized-playlist-wants-you-to-chill/",
            "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/06/img_0021.jpg?w=764&h=400&crop=1",
            "publishedAt": "2017-06-28T02:45:58Z"
        },


        {
            "author": "Josh Constine",
            "title": "Facebook now has 2 billion monthly users… and responsibility",
            "description": "Thirteen years after launching and less than five years after hitting 1 billion, Facebook now has 2 billion monthly active users. If getting to 1 billion was..",
            "url": "https://techcrunch.com/2017/06/27/facebook-2-billion-users/",
            "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/06/facebook-users-snapchat-twitter-youtube-whatsapp-instagram-wechat-qq.png?w=764&h=400&crop=1",
            "publishedAt": "2017-06-27T17:06:05Z"
        }
    ]
}

如何使用news.html.erb显示所有文章?

任何帮助都是高度赞赏的。谢谢!

2 个答案:

答案 0 :(得分:1)

问题在于:

techcrunch.articles["url"]

techcrunch["articles"]是一个数组。您可能想要遍历文章:

<% @techcrunch["articles"].each do |techcrunch| %>

并删除.articles

techcrunch["url"]

失败的地方。

答案 1 :(得分:-1)

您应该检查控制台上的api响应,看看你得到了什么并从那里开始。

def new
  ...etc
  puts @techcrunch
end

甚至在视图内部,在所有事件<%= @techcrunch %>之前 你可能是循环一个字符串而不是一个对象,错误来自于它是一个字符串,当你调用[“urlImage”]时,它应该是一个整数,表示索引而不是字符串(“urlImage”)。在迭代之前,您需要先解析并组织响应。

此外,您可以致电:

if @techcrunch.blank?

而不是.nil? &安培;&安培; == []