Cannon Moyer
Cannon Moyer

Reputation: 3174

Rails .where any field contains specific text

Is there a short-hand way of querying a Rails database for any record that has a field containing a specific piece of text? I know I could code every field with a .where("field_name LIKE ?", "my text"), but I have several fields and am wondering if there is a shorter way of doing this.

Thanks in advance.

Upvotes: 3

Views: 5030

Answers (3)

lacostenycoder
lacostenycoder

Reputation: 11226

class MyModel
    scope :search_like, -> (field_name, search_string) {where("#{field_name} LIKE ?", "%#{search_string}%")}
end

then you can call it like:

MyModal.search_like('name', 'foobar')

UPDATE based on @holgar answer but beware if not indexed these searches can be slow on large data sets:

class MyModel
  def self.multi_like(search_string)
    my_attributes = [:first_name, :last_name] # probalby only use string fields here
    queries = my_attributes.map { |attr| "#{attr} LIKE '%#{search_string}%'" }
    where(queries.join(" OR "))
  end   
end

Upvotes: 1

Holger Frohloff
Holger Frohloff

Reputation: 1705

I do not know of a framework-way to do so. You could code something using

my_attributes = YourModel.attributes
# delete attributes you do not need, like `id` etc.
# or just create an array with your desired attributes,
# whichever way is faster
queries = my_attributes.map { |attr| "#{attr} LIKE %insert_your_text_here%" } 
# Do not use this if the text your looking for is provided by user input.
built_query = queries.join(" OR ")
YourModel.where(built_query)

This could bring you closer to your goal. Let me know if this makes sense to you.

edit: The answer https://stackoverflow.com/a/49458059/299781 mentions Ransack. That's a nice gem and takes the load off of you. Makes it easier, nicer and performs better :D

Glad you like this, but pay attention that you make your app open for sql injection, if you take user-input as the text you are looking for. (with this solution) Ransack would alleviate that.

Upvotes: 5

Sanjay Prajapati
Sanjay Prajapati

Reputation: 834

If you want full fledge text search based on params then you can use ransack gem

Upvotes: 0

Related Questions