Building the SQL WHERE clause dynamically, revisited
December 9th, 2005
In Building the SQL WHERE clause dynamically in Rails, I showed how to build the WHERE clause like this:
Ezra Zygmuntowicz of brainsp.at fame
created a Cond module to make that even easier:
See Build AR::Base.find’s :conditions clause dynamically take one for the full source code.
Now, if that were turned into a plugin, wouldn’t that be nice ?
October 12th, 2007 at 10:25 PM
Hey Francis
I was having some weird troubles with the module version of this snippet. So I changed it back to a class. So the way to use it like you are above is like this:
class SearchController < ApplicationController def search conditions = Cond.new do month '<=', params[:month] year '=', params[:year] name 'LIKE', "%#{params[:name]}%" end @results = Model.find(:all, :conditions => conditions.where) end endI am thinking about making this a plugin but I need to come up with an easier way to do this. I would like to build AR::Base.find_with_conditions like this:
class SearchController < ApplicationController def search @results = Search.find_with_conditions do month '<=', params[:month] year '=', params[:year] name 'LIKE', "%#{params[:name]}%" end endThats just what I would like the interface to look like. I haven’t gotten it working that way yet. Basically it would generate the Cond object behind the scenes and then call AR::Base.find with the appropriate conditions for the where clause. But AR::Base.find calls itself recursively somewhere and i haven’t gotten around that yet.
But I will soon and then I will make a plugin.
Cheers
October 12th, 2007 at 10:25 PM
Francois-
I have done some more work on this where clause business. The newest interface adds AR::Base.find_with_conditions that you can use like this:
I think this ios a much nicer interface. I will be releasing this updated plugin in the next few days. So look for it on my blog.
Cheers