Rails 4使用javascript

时间:2015-06-21 13:15:48

标签: jquery ajax ruby-on-rails-4 search

我有一个使用Ruby 2.2.2的Rails 4.2.1应用程序。我已经使用Ransack实现了基本搜索,并使用Ajax进行远程调用以防止搜索时出现页面加载。

我正在尝试使用jQuery keyup功能,因此当用户开始在搜索框中输入时,它将实时生成结果。以下是我的代码。我在application.js中编写的jQuery / JS在Rails 3.2.x应用程序中运行良好(我之前将其从之前删除),但它在Rails 4.2.1中根本不起作用。

的application.js

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

index.js.erb的

$("#search").html("<%= escape_javascript render("search") %>");
$("#results").html("<%= escape_javascript render("results") %>");

_search.html.erb

  <div class="pull-right" style="margin-right: 25px">
    <%= search_form_for(@q, url: "/inventory", method: :get, :id => "inventory_search", :remote => true) do |f| %>
      <%= f.search_field :asset_number_or_asset_name_or_asset_serial_cont, placeholder: 'Search...', class: 'form-control' %>
    <% end %>
  </div>

_results.html.erb

<table class="table table-striped">
  <thead>
    <tr>
      <th>Asset Number</th>
      <th>Asset Name</th>
      <th>Serial Number</th>
      <th>Model</th>
      <th>Manufacturer</th>
      <th>Asset Type</th>
      <th>Actions</th>
    </tr>
  </thead>

  <tbody>
   <% @assets.each do |a| %>      
      <tr>
        <td><%= a.asset_number %></td>
        <td><%= a.asset_name %></td>
        <td><%= a.asset_serial %></td>
        <td><%= a.asset_model %></td>
        <td><%= a.asset_manuf %></td>
        <td><%= a.asset_type.try(:name) %></td>
        <td><%= link_to 'View', inventory_path(a), :class => 'btn btn-mini btn-info' %> <%= link_to 'Edit', edit_inventory_path(a), :class => 'btn btn-mini btn-warning' %></td>

      </tr>
  </tbody>
  <% end %>
<%= will_paginate @assets %>
输入

时输入

编辑日志摘录

Started GET "/inventory?utf8=%E2%9C%93&q%5Basset_number_or_asset_name_or_asset_serial_cont%5D=di&_=1434896540287" for 127.0.0.1 at 2015-06-21 09:22:22 -0500
Processing by InventoryController#index as JS
  Parameters: {"utf8"=>"✓", "q"=>{"asset_number_or_asset_name_or_asset_serial_cont"=>"di"}, "_"=>"1434896540287"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Rendered inventory/_search.html.erb (1.5ms)
  Asset Load (0.3ms)  SELECT  "assets".* FROM "assets" WHERE (("assets"."asset_number" ILIKE '%di%' OR "assets"."asset_name" ILIKE '%di%') OR "assets"."asset_serial" ILIKE '%di%')  ORDER BY asset_number ASC LIMIT 10 OFFSET 0
  Rendered inventory/_results.html.erb (1.1ms)
  Rendered inventory/index.js.erb (22.8ms)
Completed 200 OK in 59ms (Views: 52.5ms | ActiveRecord: 3.2ms)

正如你可以看到Ajax正在触发并捕获我的输入,在这种情况下我输入“di”但没有显示结果,而且如果我清除该字段它也不会返回所有默认的范围结果。

对此的任何帮助或指导将不胜感激。如果我的问题不明确或您需要进一步的信息,请询问!

0 个答案:

没有答案