這可能是一個概念問題而不是語法問題,但是我希望能夠提供有關如何解決問題的任何輸入。過去幾天我一直在困惑它,並且遇到了困難。如何使用表單數據更新模型的類方法
下面是對這種情況的總體概述,我將在下面詳細介紹。
我希望用戶能夠輸入他/她的郵政編碼,然後根據該郵政編碼返回天氣預報。
這是我目前有:
應用程序/模型/ 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