0

I have several records for which title starts with:

  • Nick1
  • Nick2
  • Nick3
  • Othername1

How can I select all the records of which the title starts with "Nick" and have them rendered in the correct order? Something like:

@records = Record.where(title starts with: params[:title_name])
render json: @records
Nick
  • 3,496
  • 7
  • 42
  • 96

3 Answers3

2

You can use the LIKE operator here:

@records = Record.where('title LIKE ?', "#{params[:title_name]}%").order(:title)

I would prefer to put these into a scope:

scope :title_search, ->(title){ where('title LIKE ?', "#{title}%") }

and call it via:

@records = Record.title_search(params[:title_name])
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
rob
  • 2,136
  • 8
  • 29
  • 37
  • 1
    For “**started** with certain string” the correct placement of a percent sign would be the opposite: `'title LIKE ?', "#{title}%"`. – Aleksei Matiushkin Feb 10 '16 at 12:23
  • @mudasobwa thanks a lot. you're right. i updated the answer and correct my mistake – rob Feb 10 '16 at 12:28
  • Thanks, it works but I'm having a problem with capital sensitivity. The title in the params is without a capital, while in the database the title has a capital. As a results it returns no records. Is there a way to solve this and make the 'query' capital insensitive? – Nick Feb 10 '16 at 12:47
  • 2
    Try `Record.where('LOWER(title) LIKE ?', "#{params[:title_name].downcase}%").order(:title)` to be caseinsensitive. The SQL function could also be `LCASE`. Depends on your database. – sschmeck Feb 10 '16 at 12:57
0

You can try Searchlogic .

Then it's as easy as:

@search = Record.new_search(params[:search])
@search.condition.title_starts_with = "Nick"
@models = @search.all

Or you can try

Record.where("title LIKE :prefix", prefix: "#{prefix}%")
Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
0

I'd recommend using arel as in "How to do a LIKE query in Arel and Rails?"

records = Record.arel_table
Record.where records[:title].matches("#{params[:title_name]}%")
Community
  • 1
  • 1
ReggieB
  • 8,100
  • 3
  • 38
  • 46