【问题标题】:Rails Search form works only after reloading pageRails 搜索表单仅在重新加载页面后有效
【发布时间】:2016-10-22 16:43:59
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      您的 turbolinks 可能会遇到此错误。试试这个ready

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

      【讨论】:

        猜你喜欢
        • 2013-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-23
        • 2014-03-25
        • 1970-01-01
        相关资源
        最近更新 更多