Ruby on Rails:将表单输入转换为模型

时间:2015-04-09 01:02:04

标签: ruby-on-rails ruby api wunderground

我还在学习更多有关Rails的知识,我开始使用API​​,但我似乎无法弄清楚如何从表单获取输入到模型。

我想接受用户输入(以邮政编码的形式)并让它在该用户位置吐出天气信息。

home.html.erb

上的表格
<%= form_tag(root_path) do %>
  <%= label_tag :zip, "ENTER YOUR ZIPCODE TO FIND YOUR WEATHER"  %><br>
  <%= text_field_tag :zip,'', placeholder: "e.g. 91765 " %>
  <%= submit_tag "show me the weather!" %>
<% end %>

Controller pages_controller.rb

class PagesController < ApplicationController

  def home
    @weather_lookup = WeatherLookup.new(params[:zip])
  end
end

模型weather_lookup.rb

class WeatherLookup
  attr_accessor :temperature, :weather_condition, :city, :state, :zip

  def initialize(zip)
    self.zip = zip
    zip = 91765 if zip.blank?
    weather_hash = fetch_weather(zip)
    weather_values(weather_hash)
  end

  def fetch_weather(zip)
    p zip
    HTTParty.get("http://api.wunderground.com/api/API-KEY-HERE/geolookup/conditions/q/#{zip}.json")
  end

  def weather_values(weather_hash)
    self.temperature = weather_hash.parsed_response['current_observation']['temp_f']
    self.weather_condition = weather_hash.parsed_response['current_observation']['weather']
    self.city = weather_hash.parsed_response['location']['city']
    self.state = weather_hash.parsed_response['location']['state']
  end
end

我不确定如何从表单输入模型。这只是为了显示天气。我不是想在数据库中保存任何东西

2 个答案:

答案 0 :(得分:0)

在您点击提交后,您似乎没有点击您的家庭控制器。确保使用

正确路由
root to: 'pages#home'

并将其添加到您的表单

<%= form_tag(root_path, method: 'get') do %>

答案 1 :(得分:0)

表单助手默认为&#34; POST&#34;如果你没有提供方法。从控制器的外观来看,&#34; GET&#34;是你想要的。 Here's some documentation提供额外的背景信息。更新后的表格:

<%= form_tag(root_path, method: "get") do %>
    <%= label_tag :zip, "ENTER YOUR ZIPCODE TO FIND YOUR WEATHER"  %><br>
    <%= text_field_tag :zip,'', placeholder: "e.g. 91765 " %>
    <%= submit_tag "show me the weather!" %>
<% end %>

接下来,如果您尝试在没有@weather_lookup的情况下实例化params[:zip]变量,Rails将抛出错误。向控制器添加条件将解决此问题:

class PagesController < ApplicationController

  def home
    if params[:zip]
      @weather_lookup = WeatherLookup.new(params[:zip])
    end
  end

end

确保您的路线已设置。 root中应该存在定义routes.rb的内容。例如:

  root "pages#home" 

我相信你还必须将JSON解析为模型中的哈希。将其添加到weather_values方法:

  def weather_values(weather_json)
    weather_hash = JSON.parse weather_json
    self.temperature = weather_hash.parsed_response['current_observation']['temp_f']
    self.weather_condition = weather_hash.parsed_response['current_observation']['weather']
    self.city = weather_hash.parsed_response['location']['city']
    self.state = weather_hash.parsed_response['location']['state']
  end

最后,请确保您在视图中的某个位置引用@weather_lookup,否则数据不会显示。一个简单的,未格式化的例子:

<%= @weather_lookup %>

假设逻辑在您的模型中有效,JSON应该在您通过表单提交邮政编码后呈现。我没有API密钥,否则我会自己测试一下。