3

Is there a way to automatically wrap all searches with a wildcard?

e.g.:

 Book.search("*${params.q}*", params)
Nix
  • 57,072
  • 29
  • 149
  • 198
  • Can you try it in the UrlMapping (http://grails.org/doc/latest/guide/single.html#urlmappings) using the Arbitrary Variables? – James Zhang Mar 14 '13 at 18:13

1 Answers1

2

I'm not familiar with .search (are you using a plugin?). However, for a wildcard search in models, I typically create a method inside the domain model class. In your example,

In the Book model class:

class Book {
   String title
   String author
   int year

   static List wildSearch(par, val) {
      def foundList = this.executeQuery("select b FROM Book b WHERE ${par} like \'%${val}%\'")
      return foundList
   }
}

In your controller:

def searchBook = {
   def b1 = new Book(title: "Farewell To Arms", author: "Ernest Hemingway").save()
   def b2 = new Book(title: "The Brother's Karamazov", author: "Anton Chekov").save()
   def b3 = new Book(title: "Brothers in Arms", author: "Cherry Dalton").save()

   // If you search for "Arms", This returns b1 and b3 
   def found = Book.wildSearch("title", params.title)
}

Example URL:

http://localhost:8080/mytest/mycontroller/searchBooks?title=Arms    
ibaralf
  • 12,218
  • 5
  • 47
  • 69
  • Searchable is a grails plugin that makes searching a little easier. Thanks for the suggestion but I would like to find out if there is a way to default the plugin. – Nix Mar 14 '13 at 13:13
  • Should have read your question title more closely. Sorry about that. – ibaralf Mar 14 '13 at 17:04