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 %>

4 Answers 4

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.

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

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.

2
  • Thanks. I've omitted some of the extra fluff. Let me try out your answer. Dec 31, 2013 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? Dec 31, 2013 at 23:17
0

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

@guides = Guide.where("title LIKE %attack%")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.