Reputation: 1017
I am trying to add the ability to search records based on a from/to date range.
class Search < ActiveRecord::Base
has_many :documents
# The code below sets up scopes based on the search/input form entries.
def search_documents
documents = Document.all
documents = documents.where("subject like ?", "%#{subject}%") if subject.present?
documents = documents.where("body like ?", "%#{text}%") if text.present?
documents = documents.joins(:category).where("categories.name like ?", "%#{category}%") if category.present?
documents = documents.joins(:author).where("authors.name like ?", "%#{author}%") if author.present?
documents = documents.joins(:reviewer).where("reviewers.name like ?", "%#{reviewer}%") if reviewer.present?
documents = documents.where("created_at >= ?", "{from_date}") if from_date.present?
The first five lines work fine. The problem is the last line with the date. The way it is now, I get no records. I.e the database has records with a created_at
date of 10/5/2015 through 10/21/2015, but if I enter 10/15/2015, I get no records even though there are records created after that date.
From date comes from a form with a model. The schema is:
t.date "from_date"
Upvotes: 0
Views: 50
Reputation: 1830
You need to re write your code like this
documents = documents.where("created_at >= ?", from_date) if from_date.present?
Upvotes: 2