Вот мой полный код, если кому-то интересно. Этот код наблюдает «поиск» text_field_tag каждые 2 секунды, и если происходит изменение значения, он запускает поиск автоматически. Думаю, теперь с кнопкой «Отправить» можно покончить. Я мог бы добавить :autocomplete => "off", :onKeyPress=>"return disableEnterKey(event)") %>
к text_field_tag, чтобы отключить ключ возврата, не уверен.
В моем index.html.erb у меня есть:
<h1>Listing homepages</h1>
<div id = "testsearch">
<%=render :partial => 'homepage'%>
</div>
<%= form_tag homepages_path, :method => 'get', :remote => true do %>
<%= label_tag(:search, "Search for:") %>
<%= text_field_tag :search, params[:search]%>
<%= submit_tag "search", :name => nil %>
<%end%>
<%= set_focus_to_id 'search' %> // I have a helper "set_focus_to_id"
<script>
document.observe("dom:loaded", function() { // ensures the page is loaded first
new Form.Element.Observer( // Observes the text_field_tag every 2 seconds
'search',
2,
respondToChange //refrences the function in the Layout <head>
) // on a change in search calls respondToChange
});
</script>
<br />
<%= link_to 'New Homepage', new_homepage_path %>
В моем приложении Layout head у меня есть:
<script>
function respondToChange() {
$('search').up('form').submit() // The ".up finds the form in the DOM"
};
</script
В моем контроллере # index у меня есть:
def index
@homepages = Homepage.search(params[:search]) //".search method is in the Model"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @homepages }
format.js
end
end
В моей модели: 1013 *
def self.search(search_item)
if search_item
self.where('section LIKE ?', "%#{search_item}%") //Handles the ajax call.
else
self.all //Handles the html call on startup.
end
end
В помощнике у меня есть:
def set_focus_to_id(id)
javascript_tag("$('#{id}').focus()");
end
В части "_homepage" у меня есть:
<table>
<tr>
<th>Id</th>
<th>Section</th>
<th>Link</th>
<th>Description</th>
<th></th>
<th></th>
<th></th>
</tr>
<% for homepage in @homepages %>
<tr>
<td><%= homepage.id %></td>
<td><%= homepage.section %></td>
<td><%= homepage.link %></td>
<td><%= homepage.description %></td>
<td><%= link_to 'Show', homepage %></td>
<td><%= link_to 'Edit', edit_homepage_path(homepage) %></td>
<td><%= link_to 'Destroy', homepage, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<%end%>
</table>
А в index.js.erb у меня есть:
$('testsearch').update("<%= escape_javascript(render :partial => 'homepage') %>");
Если у кого-то есть какие-либо комментарии о том, как я могу улучшить это, пожалуйста, свяжитесь со мной или скажите.