0

我有这个代码:

模型:

class WeatherLookup 
    attr_accessor :temperature, :icon, :condition, :zip, :fcttext

    def fetch_weather(city)
      HTTParty.get("http://api.wunderground.com/api/api_key/forecast/lang:NL/q/IT/#{city.slug}.xml")
     end

    def initialize
      weather_hash = fetch_weather
    end

    def assign_values(weather_hash)
      hourly_forecast_response = weather_hash.parsed_response['response']['forecast']['txt_forecast']['forecastdays']['forecastday'].first 
      self.fcttext = hourly_forecast_response['fcttext']
      self.icon = hourly_forecast_response['icon_url']

   end


   def initialize(city)  
    @city = city
    weather_hash = fetch_weather(city)
    assign_values(weather_hash)
   end

end

城市控制器:

@weather_lookup = WeatherLookup.new(@city)

城市景观:

 = @weather_lookup.fcttext 
        = image_tag @weather_lookup.icon

这项工作很好......我得到了 forecastdays 容器的第一个数据集。来自 api 的 xml 如下所示:

<response>
<version>0.1</version>
<termsofService>
http://www.wunderground.com/weather/api/d/terms.html
</termsofService>
<features>
<feature>forecast</feature>
</features>
<forecast>
<txt_forecast>
<date>2:00 AM CEST</date>
<forecastdays>
<forecastday>
<period>0</period>
<icon>clear</icon>
<icon_url>http://icons-ak.wxug.com/i/c/k/clear.gif</icon_url>
<title>zondag</title>
<fcttext>
<![CDATA[ Helder. Hoog: 86F. Light Wind. ]]>
</fcttext>
<fcttext_metric>
<![CDATA[ Helder. Hoog: 30C. Light Wind. ]]>
</fcttext_metric>
<pop>0</pop>
</forecastday>
<forecastday>
<period>1</period>
<icon>clear</icon>
<icon_url>http://icons-ak.wxug.com/i/c/k/clear.gif</icon_url>
<title>zondagnacht</title>
<fcttext>
<![CDATA[ Helder. Laag: 61F. Light Wind. ]]>
</fcttext>
<fcttext_metric>
<![CDATA[ Helder. Laag: 16C. Light Wind. ]]>
</fcttext_metric>
<pop>0</pop>
</forecastday>
<forecastday>
<period>2</period>
<icon>partlycloudy</icon>
<icon_url>http://icons-ak.wxug.com/i/c/k/partlycloudy.gif</icon_url>
<title>maandag</title>
<fcttext>
<![CDATA[ Gedeeltelijk bewolkt. Hoog: 84F. Light Wind. ]]>
</fcttext>
<fcttext_metric>
<![CDATA[ Gedeeltelijk bewolkt. Hoog: 29C. Light Wind. ]]>
</fcttext_metric>
<pop>20</pop>
</forecastday>
<forecastday>
<period>3</period>
<icon>clear</icon>
<icon_url>http://icons-ak.wxug.com/i/c/k/clear.gif</icon_url>
<title>maandagnacht</title>
<fcttext>
<![CDATA[ Gedeeltelijk bewolkt. Laag: 63F. Light Wind. ]]>
</fcttext>
<fcttext_metric>
<![CDATA[ Gedeeltelijk bewolkt. Laag: 17C. Light Wind. ]]>
</fcttext_metric>
<pop>0</pop>
</forecastday>

我想通过循环访问预测容器中的所有预测,但是当我将 hourly_forecast 变量(.first)更改为 .all 或 none 时,我收到错误消息“无法将字符串转换为整数”

有人想解决这个问题吗?\

4

1 回答 1

0

hourly_forecast中删除.first 后,您现在将返回一个集合,而不是单个项目。这意味着您的视图将无法正常工作,因此您需要更新视图以呈现集合。这最好用部分来完成。

city_view 将变为:

= render partial: "weather_lookup", collection: @weather_lookup

然后创建一个名为_weather_lookup.html.haml的部分并包括以下内容:

= @weather_lookup.fcttext 
        = image_tag @weather_lookup.icon

部分文件名前面的下划线很重要,因为这是 Rails 约定,所以不要忽略它。查看时,将为集合中的每个项目多次呈现部分。

于 2012-09-09T12:47:20.717 回答