Spotify Search API,如何设置查询参数以动态地等于搜索表单中的用户输入

时间:2015-10-22 19:58:51

标签: ruby-on-rails api parameters

我正在尝试构建一个搜索表单,允许用户通过Spotify API在Spotify上搜索艺术家。只要params [:query]已经定义,我就能够获得Spotify的数据并搜索艺术家,但显然我希望将params [:query]定义为用户输入的任何搜索输入。 Rails的新手,我该怎么做?到目前为止我所拥有的......

导航到我的艺术家搜索页面(artists / index.html.erb)时收到的错误消息,而没有定义params [:query]:

NoMethodError in ArtistsController#index
undefined method `encoding' for nil:NilClass

问题专栏:

response = HTTParty.get("https://api.spotify.com/v1/search?q=#{CGI.escape @query}&type=artist")

artists_controller.rb:

class ArtistsController < ApplicationController
  def index
    response = HTTParty.get("https://api.spotify.com/v1/search?q=#{CGI.escape params[:query]}&type=artist")
    @hash_version = JSON.parse(response.body)
  end
end

我的搜索表单以及我如何搜索艺术家

艺术家/ index.html.erb:

<h1>Artist Search</h1>
<i>(search for artists you would like to follow)</i>
<br>
<br>
<%= form_tag("/search", method: "get") do %>
  <div class="form-group">
    <%= label_tag(:query, "Search artist by name:") %>
    <%= text_field_tag(:query, "", class: 'form-control', autofocus: true, placeholder: "Enter artist name") %>
  </div>
  <div class="form-group">
    <%= submit_tag("Search", class: 'btn btn-success') %>
  </div>
<% end %>

<% @hash_version["artists"]["items"].each_with_index do |band, index| %>
  <% if index == @hash_version["artists"]["items"].size - 1 %>
    <li class="artist_li">
      <%= image_tag(band["images"].first["url"], class: 'img-responsive artist_img') rescue image_tag("microphone.png", class: 'img-responsive artist_img mic_bg') %>
      <br>
      <h1 class="artist_name"><%= band["name"] %></h1>
      <br>
      <% if band["genres"].empty? %>
        <h5>no genres</h5>
      <% else %>
        <h5><%= band["genres"] %></h5>
      <% end %>
      <br>
      <h5><%= band["followers"]["total"] %> followers</h5>
      <br>
      <h4>(Follow)</h4>
      <!-- no hr with last li -->
    </li>
  <% else %>
    <li class="artist_li">
      <%= image_tag(band["images"].first["url"], class: 'img-responsive artist_img') rescue image_tag("microphone.png", class: 'img-responsive artist_img mic_bg') %>
      <br>
      <h1 class="artist_name"><%= band["name"] %></h1>
      <br>
      <% if band["genres"].empty? %>
        <h5>no genres</h5>
      <% else %>
        <h5><%= band["genres"] %></h5>
      <% end %>
      <br>
      <h5><%= band["followers"]["total"] %> followers</h5>
      <br>
      <h4>(Follow)</h4>
      <hr class="artists_hr">
    </li>
  <% end %>
<% end %>

0 个答案:

没有答案