Rails搜索表单仅在重新加载页面后起作用

时间:2016-10-22 16:44:00

标签: javascript jquery ruby-on-rails ruby-on-rails-4

我在Slips视图中有一个搜索表单,可以在div中动态显示Anagraphic模型的结果。问题是,当第一次加载滑动索引页面时,搜索不能动态地工作,而是仅在按下搜索按钮之后。重新加载页面后,搜索工作正常,在搜索字段中输入字符后动态显示结果。

这是我的Anagraphic模型

def self.search(search)
 if search
  where('description LIKE :search OR code LIKE :search ', search: "%#{search}%")
 else
   all.limit(2)
 end
end

这是我的SlipsController:

def index

  @visibleanagraphics = Anagraphic.where("laundryowner_id = ?", current_owner.id)
  @anagraphics = @visibleanagraphics.search(params[:search])

  respond_to do |format|
   format.js
   format.html
  end

end

在我的单曲索引视图中,我有:

<%= form_tag '/slips', :method => 'get', :id => "anagraphics_search" do %>
  <%= text_field_tag :search, params[:search], :autocomplete => :off %>
  <%= submit_tag "°", :description => nil, class:"btn btn-primary btn-sm" %>

  <div id="anagraphics">
    <%= render "anagraphics" %>
  </div>
   

结果显示在此部分中:

<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Codice</th>
            <th>Descrizione</th>
            <th>Cliente</th>
            <th colspan="1"></th>
        </tr>
    </thead>
    <tbody>
      <% @anagraphics.each do |anagraphic| %>
        <tr>
          <td><%= anagraphic.code %></td>
          <td><%= anagraphic.description %></td>
          <td><%= anagraphic.customer %></td>
          <td><%= link_to 'crea cedolino', {controller: 'slips', action: 'new', aid: anagraphic.id}, class: "btn btn-primary btn-sm" %></td>
        </tr>
      <% end %>
    </tbody>
</table>

这是javascript代码slips.js

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

最后我的index.js.erb:

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

2 个答案:

答案 0 :(得分:0)

可能是因为您启用了turbolinks。这会影响你的jQuery的$(document).ready(function () {...})调用,因为turbolinks基本上会缓存页面并且只在你刷新时重新加载整个页面,这就是为什么它在你之后可能正在工作的原因。< / p>

好的选择是尝试使用旨在解决此问题的gem jquery.turbolinks。请参阅以下链接,了解如何将其添加到您的应用中:

https://github.com/kossnocorp/jquery.turbolinks

答案 1 :(得分:0)

你可能会因turbolinks而犯这个错误。请改为ready

$(document).on('turbolinks:load', function() {
  $("#anagraphics_search input").keyup(function() {
    $.get($("#anagraphics_search").attr("action"), $("#anagraphics_search").serialize(), null, "script");
    return false;
  });
});