使用帮助方法Rails AJAX实时搜索

时间:2015-06-02 17:51:38

标签: javascript ruby-on-rails ruby ajax ruby-on-rails-3

我正在尝试复制Spotify搜索,在每次按键时都会更新搜索结果。它目前适用于提交,但在按键时,我在我的控制台中收到错误的请求错误。如何在按键上更新我的页面?一些背景信息:我在搜索条目中调用的辅助方法中使用RSpotify gem。

static_controller.rb:

class StaticController < ApplicationController
  include ApplicationHelper

  def home
  end

  def search
    @search = user_search(params[:query])

    render :home

  end
end

application_helper.rb:

module ApplicationHelper

def artist_search(query)
    artists = RSpotify::Artist.search(query)
  return artists
end

def track_search(query)
  tracks = RSpotify::Track.search(query)
  return tracks
end

def album_search(query)
  albums = RSpotify::Album.search(query)
  return albums
end

def user_search(query)
  results = {"artist" => artist_search(query), "tracks" => track_search(query), "album" => album_search(query)}
  return results
end

end

home.html.erb:

<%= form_tag search_path, method: :get, :id => "search" do %>
    <%= text_field_tag :query %>
    <%= submit_tag 'Search' %>
<% end %>

<% if params.include?(:query) %>
    <div id="music"><%= render 'music' %></div>
<% end %>

_music.html.erb:

<h1>Artists</h1>
<div class="ui cards">
    <% @search["artist"].each do |artist| %>
      <div class="card">
        <!-- Artist image should go here -->
        <div class="content">
          <a class="header"><%= artist.name %></a>
        </div>
      </div>
    <% end %>
</div>

<h1>Albums</h1>
<div class="ui cards">
<% @search["album"].each do |album| %>
  <div class="card">
    <a class="image">
      <img src="<%= album.images.first["url"] %>">
    </a>
    <div class="content">
      <a class="header"><%= album.name %></a>
    </div>
  </div>
<% end %>
</div>

<h1>Songs</h1>
<% @search["tracks"].each do |song| %>
    <div class="ui list">
      <div class="item">
        <img class="ui avatar image" src="<%= song.album.images.first["url"] %>">
        <div class="content">
          <a class="header"><%= song.name %></a>
          <div class="description"><%= song.album.name %></div>
        </div>
      </div>
    </div>
<% end %>

index.js.erb的:

$("#music").html("<%= escape_javascript(render("music")) %>")

的application.js:

$(function() {
  $("#search input").keyup(function() {
    $.get($("search").attr("action", $("#search").serialize(), null, "script"));
    return false;
  });
});

0 个答案:

没有答案