How to search by id or name in Active Record using meta search?

1k views Asked by At

I have an model, say:

class MyModel <ActiveRecord::Base
  attr_accessible :id, :name
end

I want to search this model using meta_search (https://github.com/ernie/meta_search), How can I search by id or name?

I tried this but does not work:

MyModel.search(id_equals_or_name_contains: 'sample text')

The meta search document says they don't support different match type (https://github.com/ernie/meta_search#ored-conditions), so How should I achieve this?

1

There are 1 answers

0
lucas On

Are you expecting the sample text to either be an integer or a string? If so you could implement a simple conditional using the function described here: Test if a string is basically an integer in quotes using Ruby?

s = 'sample text'
if !!(s =~ /^[-+]?[0-9]+$/)
  MyModel.search(id_equals: s.to_i)
else
  MyModel.search(name_contains: s)
end