繁体   English   中英

Rails Search表单仅在重新加载页面后可用

[英]Rails Search form works only after reloading page

我在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")) %>")

可能是因为您启用了Turbolink。 这将影响您的jQuery的$(document).ready(function () {...})调用,因为Turbolinks基本上会缓存该页面,并且仅在刷新时才重新加载整个页面,这就是为什么它可能在您刷新起作用这样做。

不错的选择是尝试使用gem jquery.turbolinks来解决此问题。 通过以下链接查看如何将其包含在您的应用中:

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

Turbolinks可能有此错误。 试试这个代替ready

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM