Leahcim
Leahcim

Reputation: 41919

syntax error when ordering by date

I'm using postgresql for a database on a Rails app that keeps track of when certain events take place. The database column for when the event takes place is called when (bad name, I know). I can do this

@events = @group.events.order('created_at DESC')

However, when I do this

 @events = @group.events.order('when DESC')

I get this error

PG::SyntaxError: ERROR:  syntax error at or near "when"
LINE 1: ..."events"  WHERE "events"."group_id" = $1  ORDER BY when DESC
                                                              ^
: SELECT "events".* FROM "events"  WHERE "events"."group_id" = $1  ORDER BY when DESC

A when record has this format in the database

when: "2013-08-07"

Based on what I've told you, can you see the reason why I can't do this

@events = @group.events.order('when DESC')

It's important for me to be able to order the events by when they are being held. Since ordering by created_at works, I don't see why the syntax error arises when I substitute a different column.

Upvotes: 0

Views: 657

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

  • WHEN is a reserved word in SQL (think about the Switch cases: CASE <smth> WHEN ...)

  • You can try accessing it like this:

    Event.order('events.when DESC')
    
  • You should change your column's name to something different than when (Take a look at @PhilipHallstrom comment)

Upvotes: 3

Related Questions