开发者

MongoID and multikey query problem

I have a model Item with an indexed field named _key, that 开发者_运维问答is array of strings (keywords for search). Now I need to do autocompletion for this model (through JSON) in another form, and the problem is that instead of exact search by all words input by user, I need to do exact search by all but one last word. So I made this scopes in this model:

scope :find_by_keywords, lambda { |keys| where(:_keys.all => keys) }
scope :for_autocomplete, lambda { |keys| where(:_keys.all => keys[0..-2], :_keys => /^#{keys[-1]}/i ) }

the first scope for exact search works well, but I have problems with second scope for autocomplete. MongoID optimises (or something like) this query, so it becomes

db_development['items'].find({:_keys=>/^qwer/i}, {})

i.e. it allways misses the first condition. It's not surprising, because it needs different criterias on field for different conditions. So I have tried many-many options. Different combinations of .all and .in, separate to different 'wheres', 'all_in' method, 'find(:conditions => ...)' and so on. Could you please suggest, how I can do this job?


I've found such solution:

scope :for_autocomplete, lambda { |keys| where(:_keys.all => keys[0..-2]+ [ /^#{keys[-1]}/ ] ) }

Seems to be working.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜