[英]Ruby on Rails: Getting Form Input to Model
我仍在學習有關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 %>
控制器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
我不確定如何從表單輸入到模型。 這實際上只是為了顯示天氣。 我沒有在數據庫中保存任何內容
似乎在您單擊“提交”后,您沒有再單擊家庭控制器。 確保正確路由
root to: 'pages#home'
並將其添加到您的表單
<%= form_tag(root_path, method: 'get') do %>
如果您不提供方法,則表單幫助程序默認為“ POST”。 從控制器的外觀來看,“ GET”就是您想要的。 這是一些提供其他上下文的文檔 。 更新后的表格:
<%= 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 %>
接下來,如果您嘗試在不使用params[:zip]
情況下實例化@weather_lookup
變量,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密鑰,否則我自己會對此進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.