Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Last active December 21, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammcarth/6303176 to your computer and use it in GitHub Desktop.
Save adammcarth/6303176 to your computer and use it in GitHub Desktop.
SQL syntax to execute a search from query string.
# URL Visiting: example.com/posts?search=My+search+text&m=aug&y=13
search_sql = "MATCH (title,tags) AGAINST ('query_string('search')' IN BOOLEAN MODE)"
#=> MATCH (title,tags) AGAINST ('My search text' IN BOOLEAN MODE)
month_sql = "created_at LIKE ('%-#{return_month_number(query_string('m'))}-%')"
#=> created_at LIKE ('%-08-%')
year_sql = "MATCH (created_at) AGAINST ('#{(Time.now.strftime('%Y')[0..1]).to_s + query_string('y').to_s}' IN BOOLEAN MODE)"
#=> MATCH (created_at) AGAINST ('2013')
Post.where(
[search_sql, month_sql, year_sql].compact * " AND "
)
# Intended Final SQL Output
#=> `post` WHERE (
#=> MATCH (title,tags) AGAINST ('My search text' IN BOOLEAN MODE) AND
#=> created_at LIKE ('%-08-%') AND
#=> MATCH (created_at) AGAINST ('2013')
#=> )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment