When I write city in field and click button, on page has to be that name of city and another. In my case every time name is New York. When I write for example Las Vegas my link is http://localhost:3000/?query=Las+Vegas&commit=Search
, the data on the page is about New York.
class HomeController < ApplicationController
def index
require 'net/http'
require 'json'
@params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
@uri = URI("http://api.weatherstack.com/current?access_key=1dbc1a3aa6b2e76a0c8eda1cba0c9c8b&query=#{@params[:query]}")
@uri.query = URI.encode_www_form(@params)
@json = Net::HTTP.get(@uri)
@api_response = JSON.parse(@json)
if @params[:query].empty?
@city = "Enter city"
@temperature = "(in English)"
else
@city = " #{@api_response['location']['name']}"
@temperature = "#{@api_response['current']['temperature']}°"
end
end
end
routes.rb
Rails.application.routes.draw do
root 'home#index', :as => 'search'
end
index.html.erb
<div class="main">
<h1 class="weather">Weather</h1>
<%= form_with(url: search_path, method: "get", local: true) do %>
<%= text_field_tag(:query) %>
<%= submit_tag("Search",class: "btn btn-primary") %>
<% end %>
<div class="city"> <h1><%= @city %> <h5><%= @temperature %></h5></h1> </div>
</div>
It looks like you have hardcoded New York in your params.
@params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
So you need to change this to be something like:
@params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => params[:query]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.