0

I'm trying to display all Guides where title contains the word 'attack'. I do so like so:

def attack
  @guides = Guide.where(title: 'attack')
end

Quick question - How do I make it non case-sensitive and restrictive? It can contain any spelling of the word 'attack' like 'AtTaCK', and it can have more words. As long as Attack is in it somehow.

Then, to print them out in the view, I do this:

<% @guides.each do |guide| %>
  <%= guide.title %>
<% end %>
Dylan Richards
  • 708
  • 1
  • 13
  • 33

4 Answers4

3

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table
Guide.where(t[:title].matches('%attack'))

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

zeantsoi
  • 25,857
  • 7
  • 69
  • 61
1

You can use the lower function:

Guide.where("lower(title)='attack'")

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

Stuart Nelson
  • 4,202
  • 2
  • 23
  • 26
  • Thanks. I've omitted some of the extra fluff. Let me try out your answer. – Dylan Richards Dec 31 '13 at 23:12
  • This answer got my items showing. But for some reason it's still only displaying the guides with a title of 'Attack'. I'd like all guides that have any variation of the word 'attack' to be shown. Any ideas? – Dylan Richards Dec 31 '13 at 23:17
1

Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search

There are a lot of answered questions in Stack Overflow with more data on this:

Example 1

Example 2

Community
  • 1
  • 1
Alex Falke
  • 2,178
  • 2
  • 14
  • 11
0

For case insensitive and anywhere in title, do...

@guides = Guide.where("title LIKE %attack%")
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53