Richard Sandilands
2005-Oct-07 22:13 UTC
Creating ''advanced'' search feature in a Rails app
Hi there Am a Rails newbie and am trying out a few things. Let''s say I have a ''books'' table and want to create a search facility across several columns of the books table. For instance, to search ''title'' and/or ''author'' and/or ''isbn'' I''m having a little trouble setting up the method to deal with the @params hash I''m getting back from the form. Some fields maybe empty of course. I assume I should be looking to use find_by_sql to create my own query string here? If so (and I suppose my lack of ruby and mysql skills is the issue here), what is the most efficient way to test the existence of a field value coming back from the form and compose the sql query accordingly? Any clues appreciated! Richard
On 10/8/05, Richard Sandilands <infoarts@gmail.com> wrote:> Hi there > > Am a Rails newbie and am trying out a few things. > > Let's say I have a 'books' table and want to create a search facility > across several columns of the books table. For instance, to search > 'title' and/or 'author' and/or 'isbn' > > I'm having a little trouble setting up the method to deal with the > @params hash I'm getting back from the form. Some fields maybe empty > of course. > > I assume I should be looking to use find_by_sql to create my own query > string here? > > If so (and I suppose my lack of ruby and mysql skills is the issue > here), what is the most efficient way to test the existence of a field > value coming back from the form and compose the sql query accordingly? > > Any clues appreciated!Consider using a single input element in which the user can enter an author, a title or an ISBN nr. Then you can do something like: q = '%' + query.downcase + '%' find_by_sql ['SELECT * FROM books WHERE lower(author) LIKE ? OR lower(title) LIKE ? OR lower(isbn) LIKE ?', q, q, q] This is what I'm doing in my latest DB front-end. I've spent days on complex search forms which were then never used, because usually users don't actually think in boolean. (The worst I did was an LDAP search form in PHP which supported much of the complexity of LDAP search strings---one of my worst recent engineering mistakes.) - Rowan -- Morality is usually taught by the immoral. _______________________________________________ Rails mailing list Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org http://lists.rubyonrails.org/mailman/listinfo/rails