I have come up with a nice little solution for building the Where
clause dynamically for the : conditions part of a find method in your
models. You can put this wherever you like and require it or you can
put it inside your model class that will use it.
Here it is:
class Where
Utility class to dynamically create the where clause
for a rails find method. Initialize expects a nested
array like: [[:project, 3], [:month, 7], [:user, 0]]
where each nested array contains a symbol of the column
name and a value to query for. Lets say that you have
this hash in your +params+ :
params = { :person => {:name => “dave” :city => “Yakima”}}
You can use this class to build the where clause like so:
where = Where.new([ [:user, params[:person][:name]], [:city,
params[:person][:city]] ])
MyModel.find(:all, :conditions => where.build_where_clause)
def initialize(options=[])
@opts = options
@opts.each do |pair|
instance_variable_set(“@#{pair[0].to_sym}”, pair[1])
end
end
def build_where_clause
q = []
ary = []
@opts.each do |pair|
iv = instance_variable_get(“@#{pair[0]}”)
unless iv.nil? || iv.to_s == ‘’
q << “#{pair[0]} = ?”
ary << iv
end
end
return [q.join(" and ")].concat(ary)
end
end # End Where
Some examples:
a = Where.new([[:project, 3], [:month, 7], [:user, 0]])
p a.build_where_clause
=> [“project = ? and month = ? and user = ?”, 3, 7, 0]
b = Where.new([[:post, 6], [:user, “admin”], [:comment, 12]])
p b.build_where_clause
=> [“post = ? and user = ? and comment = ?”, 6, “admin”, 12]
built from params. You can see that the params[:person][:state] is
empty.
this class will take that into consideration and leave that part
out of the where clause
params = {:id => 17, :person => {:city => “Yakima”, :name =>
“dave”, :state => “”}}
c = Where.new([[:user, params[:person][:name]], [:city, params
[:person][:city]], [:state, params[:person][:state]]])
p c.build_where_clause
=> [“user = ? and city = ?”, “dave”, “Yakima”]
Hope its useful to someone out there!
Cheers-
-Ezra Z.
Yakima Herald-Republic
WebMaster
509-577-7732
[email protected]