Question

I'd like to be able to create a Ransack::Search object to be passed into a search_form_for, but the initial creation of the search object queries the database, wich I don't want.

I want to show an initial blank form with Ransack::Search options to search, without calling the database.

How can I do that ?

thanks,

regards

Was it helpful?

Solution

Arel relations (ie. queries) are lazily-executed on first reference to the results, so you should find that you can create a search object and pass it to the form, without it calling the db, so long as you don't reference the .result method anywhere.

e.g.

// in your controller
my_query = MyModelClass.where{ id.gt(0) }
@q = my_query.search( params[:q] )

// in your view
search_form_for( @q, (...other options...) )

Any of these will trigger the db query to be actually performed:

- @q.results.each do |result| 
- for result in @q.results
- @q.results.count
- @q.results.to_a
- @q.results.size
// ....etc

But so long as you only use the search object for your form, it should not get executed.

Of course, if you're testing this from the console, make sure that you put ;nil at the end of the line, otherwise the console will print the last thing evaluated, which will cause the query to be run!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top