How do I search by date in PGSQL?
I am getting this error:
ActionView::Template::Error (PGError: ERROR: operator does not exist: timestamp without time zone ~~ unknown LINE 1: ... "articles" WHERE ("articles"."created_at" LIKE '2010...
I have an archive controller where I can dynamically display articles by genre and year, month and day, with whichever of those fields are available in the url. In mysqlite, I had this index action:
def index
filter_title
@articles = Article.where(:created_at.matches % date_builder, :genre.matches % genre_builder).order("created_at DESC")
respond_to do |format|
format.json { render :json => @articles }
format.xml { 开发者_StackOverflow中文版render :xml => @articles }
format.html
end
end
And this date_builder function
def date_builder
@date = ""
@date += params[:year] if !(params[:year].nil?)
@date += "-" + params[:month] if !(params[:month].nil?)
@date += "-" + params[:day] if !(params[:day].nil?)
@date += "%"
@date
end
that would use metawhere to find dates that matched the part of the string that I supplied. This worked perfectly in Sqlite. I have migrated my application onto heroku and PGSQL, and it doesn't allow me to do this. What is the solution? Thank you!
In postgres, a timestamp is not stored as a string like in sqllite:
select 'A' where localtimestamp like '2011-04-04%';
ERROR: operator does not exist: timestamp without time zone ~~ unknown
how about using >=
instead?
select 'A' where localtimestamp >= '2011-04-04';
?column?
----------
A
(1 row)
While I liked @JackPDouglas answer, I wanted to try and keep sql code out of my project as much as possible, so i ended up doing this:
...
date_builder
if !(params[:year].nil?)
@articles = Article.where(
{:created_at.gt => @datelower} &
{:created_at.lt => (@datehigher - 1.second)} &
:genre.matches % genre_builder
).order("created_at DESC")
else
...
and this method for the date:
def date_builder
if !(params[:day].nil?)
@datelower = Time.utc(params[:year], params[:month], params[:day])
@datehigher = @datelower + 1.day
elsif !(params[:month].nil?)
@datelower = Time.utc(params[:year], params[:month], 01)
@datehigher = @datelower + 1.month
elsif !(params[:year].nil?)
@datelower = Time.utc(params[:year], 01, 01)
@datehigher = @datelower + 1.year
end
end
精彩评论