dynamic ruby functions

hello,

i was wondering if the follow is possible with the rials/ruby combo.

say you have a bunch of checkboxes in the market labeled something like, box[state], box[city]

on submit of the form, is it possible to cycle through the params[:box], pulling out only the keys that were checked and then dynamically generating a find_by_ method based on the names of the checked boxes? i think that'd be pretty sweet.

this is one of those situations where you're generating a report based on which columns in the table are checked. i'd appreciate any input or alternative solutions.

I wrote a plugin called criteria_query (shameless plug) which is available at http://rubyforge.org/projects/criteriaquery , which allows you to more easily build dynamic queries. In your case, you could use this in the following way. In your controller class:

def search   pq = Person.query   params[:box].each do |k,v|     pq.eq(k.to_s, params[:search][k] )   end   @results = pq.find end

And in your view something like:

<input type="checkbox" name="box[city]" /> <input type="text" name="search[city]" /> <br/> <input type="checkbox" name="box[state]" /> <input type="text" name="search[state]" />

If you don't like the plugin, you can to manually construct the find conditions:

def search   fields =   parameters =   params[:box].each do |k,v|     fields << "#{k} = ?"     parameters << params[:search][k]   end   @results = Person.find(:all, :conditions=>[ fields.join(" AND "), parameters ]) end

Untested code off the top of my head, but let me know if you get stuck.

Cheers, Max

Max Muermann napisaƂ(a):