Voici mon code complet si quelqu'un est intéressé. Ce code observe text_field_tag "recherche" toutes les 2 secondes, et s'il y a un changement dans la valeur, il déclenche automatiquement une recherche. Le bouton de soumission peut maintenant être supprimé, je pense. Je pourrais ajouter :autocomplete => "off", :onKeyPress=>"return disableEnterKey(event)") %>
à text_field_tag pour désactiver la clé de retour, pas sûr.
Dans mon index.html.erb je:
<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 %>
Dans mon application tête de la mise en page je:
<script>
function respondToChange() {
$('search').up('form').submit() // The ".up finds the form in the DOM"
};
</script
Dans mon contrôleur index # J'ai:
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
Dans mon modèle j'ai:
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
Dans l'assistant, j'ai:
def set_focus_to_id(id)
javascript_tag("$('#{id}').focus()");
end
Dans le "_homepage" je partielle:
<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>
Et dans le index.js.erb je:
$('testsearch').update("<%= escape_javascript(render :partial => 'homepage') %>");
Si quelqu'un a des commentaires sur la façon dont je pourrais améliorer cela, s'il vous plaît contactez-moi ou dites-le.
Man, je vous suggère de travailler un peu plus sur la mise en forme de question, il est un peu en désordre. –
Merci, je viens d'apprendre comment et j'espère que je l'ai édité correctement – MDM