3

私が取り組んでいる Rails アプリは、API のデータベースです。 js を使用して、ホームページを離れずに検索を機能させます。Railsデータベースに接続するための角度がつかないようです。検索フォームは次のとおりです。

<form class="navbar-search" method="get" action="/apis/search" id="search">
    <input type="text" class="search-query" placeholder="Search" name="query" ng-model="query">
</form>

私の apis_controller.rb の検索方法は次のとおりです。

def search
    @results = Api.where("name ILIKE ? OR description ILIKE ? OR category ILIKE ?", "%#{params[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%").all
end

これが私のjs検索コントローラーです:

app = angular.module("Hapily", ["ngResource"])

@SearchCtrl = ($scope, $resource) ->
  Search = $resource('/search/:query', {query:"@query"})
  $scope.results = Search.get()

現在の検索ページ ビューは次のとおりです。

<% @results.each do |api| %>
<div class="box" ng-repeat="result in results | filter:query">
    <div class="api-favicon">
    <%= image_tag("http://www.google.com/s2/favicons?domain_url=" + api.url) %>
    </div>
    <%= link_to api.name, apipage_path(:id => api.id) %>
    <p class="category"><%= api.category %></p><br><br>
    <%= api.description %><br><br>

    Votes: <%= Vote.where("api_id = ?", api.id).count %>
    <%= link_to image_tag('grayarrow.gif'), votes_path(api_id: api.id, value: 1), method: :post  %>
</div>
<% end %>
</div>

現在、すべての API がインデックス ページに表示され、ユーザーがナビゲーション バーの検索ボックスに用語を入力すると、/search?query=searchterm にリダイレクトされますインデックスページ?私はAngularとRailsにかなり慣れていないので、ここから離れているかもしれません。どんな助けでも大歓迎です!

4

1 に答える 1

2

サーバー側のフィルタリングを使用しています

def search
    @results = Api.where("name ILIKE ? OR description ILIKE ? OR category ILIKE ?", "%#{params[:query]}%", "%#{params[:query]}%", "%#{params[:query]}%").all
end

クライアント側のフィルタリングとともに

<div class="box" ng-repeat="result in results | filter:query">

これらのうちの 1 つだけが必要です。

displayAngularJS フィルタリングのみを使用するには、サーバー コントローラーの名前を代わりに次のように変更searchし、結果がすべてになるようにします。

def display
    @results = Api.all
end

次に、jsコントローラーは次のようになります。

app = angular.module("Hapily", ["ngResource"])

@SearchCtrl = ($scope, $resource) ->
  Search = $resource('/display/')
  $scope.results = Search.get()

とあなたのページ(私が追加した入力と、角度がルビーではなくループを行うという事実に注意してください):

<input ng-model="query"/> 
<div class="box" ng-repeat="result in results | filter:query">
    <div class="api-favicon">
    <%= image_tag("http://www.google.com/s2/favicons?domain_url=" + api.url) %>
    </div>
    <%= link_to api.name, apipage_path(:id => api.id) %>
    <p class="category"><%= api.category %></p><br><br>
    <%= api.description %><br><br>

    Votes: <%= Vote.where("api_id = ?", api.id).count %>
    <%= link_to image_tag('grayarrow.gif'), votes_path(api_id: api.id, value: 1), method: :post  %>
</div>
于 2013-05-23T01:02:47.837 に答える