Skip to content

Instantly share code, notes, and snippets.

@goldnuggets24
Created January 16, 2015 14:26
Show Gist options
  • Save goldnuggets24/cc9feec349c32e416883 to your computer and use it in GitHub Desktop.
Save goldnuggets24/cc9feec349c32e416883 to your computer and use it in GitHub Desktop.
Get first 4 items returned from db where title matches searched criteria
@items += Item.where( "lower(title) ~* ?", "#{params[:s].downcase}".split(/,\s*/).map(&:strip).reject(&:empty?).first)
@items += Item.where( "lower(title) ~* ?", "#{params[:s].downcase}".split(/,\s*/).map(&:strip).reject(&:empty?).second)
@items += Item.where( "lower(title) ~* ?", "#{params[:s].downcase}".split(/,\s*/).map(&:strip).reject(&:empty?).third)
@items += Item.where( "lower(title) ~* ?", "#{params[:s].downcase}".split(/,\s*/).map(&:strip).reject(&:empty?).fourth)
@goldnuggets24
Copy link
Author

To be clear... each of these 4 statements are searching through a different member of the array I give it to search through. This for instance: '4,magic,ton,bastard' would respectively go through each of those 4 statements... with '4' evaluated by the first one, and so forth...

@Braidio
Copy link

Braidio commented Jan 17, 2015

You say different member of the array, but they are all passing the same params. Are you trying to query against an array you mean?

@goldnuggets24
Copy link
Author

The first line of code here returns results that match the first search term, the second line of code returns results matching the second term... and so on. So if I enter a search query like this: "h,horse,pizza, fred," I'll get results for each of those terms returned.

Specifically, it's looking up the title attribute of my Collection object. Does that make any sense?

To answer your question regarding what's returned when I ask what class this is: 'ActiveRecord_Relation'

Everything's working with the way I wrote this code. Just wondering if there's any way to dry it up. Thanks!!!

@goldnuggets24
Copy link
Author

Just thought of something dumb... I guess (at the very least) I could probs make the first half of this statement a variable and re-use that way...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment