2014-11-05 82 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

相关问题