这可能是一个概念问题而不是语法问题,但是我希望能够提供有关如何解决问题的任何输入。过去几天我一直在困惑它,并且遇到了困难。如何使用表单数据更新模型的类方法
下面是对这种情况的总体概述,我将在下面详细介绍。
我希望用户能够输入他/她的邮政编码,然后根据该邮政编码返回天气预报。
这是我目前有:
应用程序/模型/ forecast.rb // 通过HTTParty从外部API获取气象数据和格式XML响应,到我想要的数据。
class Forecast < ActiveRecord::Base
attr_accessor :temperature, :icon
def initialize
weather_hash = fetch_forecast
weather_values(weather_hash)
end
def fetch_forecast
HTTParty.get("http://api.wunderground.com/api/10cfa1d790a05aa4/hourly/q/19446.xml")
end
def weather_values(weather_hash)
hourly_forecast_response = weather_hash.parsed_response['response']['hourly_forecast']['forecast'].first
self.temperature = hourly_forecast_response['temp']['english']
self.icon = hourly_forecast_response['icon_url']
end
end
应用/视图/ static_pages/home.html.erb //提供了在顶部邮政编码输入形式,并提供了显示在底部
从API返回的信息的地方<div class="container">
<div class="row">
<div class="col-md-12">
<div class="search-form">
<%= form_tag("#", method: "get") do %>
<p><%= label_tag(:zipcode, "Zipcode:") %></p>
<p><%= text_field_tag(:zipcode, value = 19446) %></p>
<p><%= submit_tag("Get Weather Forecast") %></p>
<% end %>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 display">
<div class="display-info">
<h1>Forecast Info</h1>
<%= @forecast.temperature %></p>
</div>
</div>
</div>
</div>
我的问题是:
如何将表单数据从用户到模型连接?
我最好的猜测是建立其实例化一个类模型的形式,调用带有URL中“fetch_forecast”的方法基于用户输入,沿着这些路线的东西:
def fetch_forecast(input)
HTTParty.get("http://api.wunderground.com/api/10cfa1d790a05aa4/hourly/q/"+input+".xml")
end
然而,我不知道这是正确的还是可能的,如果是这样,我不知道如何去做这件事。
任何建议或指示不止欢迎,并感谢您的帮助。
您将使用ajax,否则ypu不会向服务器发起请求。一旦你这样做,请求一个行动的路线,将调用此方法。 – 2014-11-05 07:22:30