Last active
December 21, 2015 11:59
-
-
Save adammcarth/6303176 to your computer and use it in GitHub Desktop.
SQL syntax to execute a search from query string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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