【发布时间】: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