2014-11-05 80 views
0

這可能是一個概念問題而不是語法問題,但是我希望能夠提供有關如何解決問題的任何輸入。過去幾天我一直在困惑它,並且遇到了困難。如何使用表單數據更新模型的類方法

下面是對這種情況的總體概述,我將在下面詳細介紹。

我希望用戶能夠輸入他/她的郵政編碼,然後根據該郵政編碼返回天氣預報。

這是我目前有:

應用程序/模型/ 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 

然而,我不知道這是正確的還是可能的,如果是這樣,我不知道如何去做這件事。

任何建議或指示不止歡迎,並感謝您的幫助。

+0

您將使用ajax,否則ypu不會向服務器發起請求。一旦你這樣做,請求一個行動的路線,將調用此方法。 – 2014-11-05 07:22:30

回答

1

模型和視圖通過控制器連接(對於MVC中的C)。首先,您需要一個控制器來處理從視圖中獲取的參數並將它們傳遞給您的模型。

在你的應用程序中很難畫出一個簡單的方法來做這件事,因爲我不知道你有什麼其他模型和一般邏輯。但草圖是這樣的:

如果天氣服務以字符串的形式返回預測,則可以在數據庫中創建表以將此預測數據存儲在某處。然後,您將使用屬性模型Forecast:「zip_code」,「forecast」,它們是字符串。

之後,你需要創建一個控制器 - ForecastsController:

def new 
    @forecast = Forecast.new 
end 

def create 
    @forecast = Forecast.new(forecast_params) 
end 

def show 
    @forecast = Forecast.find(params[:id]) 
end 

private 

#please note that here is no 'forecast' attribute 
def forecast_params 
    params.require(:forecast).permit(:zip_code) 
end 

# other standard CRUD methods ommited 

在你的模型:

class Forecast < ActiveRecord::Base 

    before_save :set_forecast 

    protected 

    def set_forecast 
    self.forecast = # GET your forecast through API with your self.zip, which user already gave you 
    end 
end 

這就是全部。 再一次:這是一個非常粗略和原始的草圖,以顯示最簡單的邏輯。

+0

謝謝你的非常全面的答案。花了我幾天的時間仔細閱讀文檔,直到一切正常點擊,但這使我朝着正確的方向前進。非常感激。 – jmknoll 2014-11-06 14:32:20

相關問題