Hi everyone,
I’ve been working on some code which will take params and turn them into
a
WHERE clause for the :conditions option in finder methods. So far I’ve
been
able to do some very simple text matching. I’d like to be able to
support
ranges, and then go from there (in fact I’ve added code for date ranges
but
I’m embarrassed of it so I won’t show it here). Is there already
something
like this out there? Also, is there any way I can make my code more
Ruby-fied?
Here’s what I have so far:
–application.rb
private
#this could probably stand to be renamed
def dynamic_conditions_from_hash(some_hash, model)
model = Class.new(model)
some_hash.delete_if { |key, value| not
model.column_names.include? key }
conditions_from_hash(some_hash)
end
def conditions_from_hash(some_hash)
condition = ‘’
some_hash.each_pair {|key, value|
if value.empty?
next
end
condition << "#{key} LIKE ‘%#{value}%’ AND "
}
condition[0…-5].to_s
end
–some_controller.rb
def list
paginator_options = {:per_page => 10}
conditions = dynamic_conditions_from_hash(params, Item)
unless conditions.empty?
paginator_options.merge!({:conditions => conditions})
end
@item_pages, @items = paginate :items, paginator_options
end
Thanks, and I hope this helps!
Daniel