a5his@gmail.com\" where :email i" />
开发者

passing hash object values as search parameter

I have a table "Email" with 开发者_如何学JAVAfield "contents" where the data are stored as hash object. I want to do search in this table with parameter "email => a5his@gmail.com" where :email is key and "a5his@gmail.com" is value of a hash object.

Thanks in advance


This search is going to be extremely inefficient. If you plan on doing lot of of searches for email, it might be prudent to add an indexed column to store the email in your table.

I am assuming contents is a text field to store a serialized Hash. The hashes are serialized using YAML format, which is in plain text. So you can perform the regular wild card searches on the content column.

Eg: A hash as shown below

{"email" => "a5his@gmail.com"}

is serialized in to string

"--- \nemail: a5his@gmail.com\n"

So you can write a simple matcher as follows:

Email.all(:conditions => ["content LIKE ? ", "%email: #{email}%"])

If you are planning on querying several dynamic fields then,

class Email < ActiveRecord::Base
  def self.find_all_by_dynamic(hash)
    ca = hash.map {|k, v| ["contents LIKE ?", "%#{k}: #{v}%"]}.transpose
    Email.all(:conditions => [ca[0].join(" AND "), *ca[1]])
  end
end

Now you can use the new method as:

Email.find_all_by_dynamic(:email => "5his@gmail.com", :zip => 94307)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜