Today I would like to introduce a new little feature for field search.
Let s assume you have a controller which shows lots of log entries and you would like to limit these log entries to the current day as a default, however if the user wants to take a look at older ones that should be also possible.

You might achieve that by using conditions_for_collection in your controller, but I think this is nt the right way.

The perfect solution for this requirement is a default field search condition. If user has nt specified a search condition we will use the default one.

Lets take a look how that might work. We do not have a log entry model, but howto app has a player model/controller.

Initially, We will setup our players controller to use fieldsearch and we will turn on human conditions:

class PlayersController < ApplicationController
  active_scaffold :player do |conf|
    conf.actions.swap :search, :field_search
    conf.field_search.human_conditions = true

The following code will enable our default search condition:

  conf.field_search.default_params = {:salary => {"from"=>"400","to"=>"", "opt"=>"<"}}

I hope you except my excuse that there is nt a nice looking dsl to define a default search condition, but I ve decided to just use the format of the field search params sent by the field search form. The easiest why to get your required default_params value is by simply submitting the field search form and copying the params from your development log.
Our default search will only list players, which have a salary below 400.

That s already a cool thing, but let s assume you have a requirement to dynamically create a default search condition, e.g. specific to the current_user. That can be implemented by using a proc. I will show you with a quite stupid example, which will change our existing hard coded 400 to a random one.

Firstly, we have to add a method to our controller which returns a random number.

  def random_salary_limit
    400 + rand(100)

Secondly, we have to adapt our existing default_params to use that random number method.

  conf.field_search.default_params = { {:salary => {"from"=> random_salary_limit.to_s, "to"=>"", "opt"=>"<"}}}

You can try it out. If you click action link on the right-hand side of human condition in your list view you hopefully will see that human conditions will change after every click.

Thanks a lot for your attention and good luck.