Search code examples
sqlruby-on-railspostgresqlruby-on-rails-4rails-postgresql

Why does Rails .select alias change attributes to lowercase?


In our controller, we are trying to show a video series, which should return JSON similar to this:

{
  id:   1,
  name: "Series Name",
  videos: [
    id:           2,
    name:         "Video Name",
    isInPlaylist: true,
    isFavorite:   false
  ]
}

We are adding the isInPlaylist and isInFavorite attributes via another table where we store data if a user has acted upon a video (rated it, favorited it, etc.).

videos = series.videos
           .where('videos.is_live = true')
           .joins("some join to user_videos join_table")
            .select(
               'videos.*,
               coalesce(user_videos.rating, 0.0) as user_rating,
               coalesce(user_videos.enqueue, \'false\') as isInPlaylist,
               coalesce(user_videos.favorite, \'false\') as isFavorite'
             )

Note that in our select statement those attributes are explicitly aliased as camel-cased values. However when we execute this query, these attributes are returned lower case instead:

{
  isinplaylist: true,
  isfavorite:   false
}

Solution

  • This is not a Rails behavior, but rather a SQL behavior. Alias's are folded to lower case unless explicitly quoted. For an example, here is the output of a simple query in psql (the Postgres CLI program).

    =# select created_at as theTimeNow from users limit 5;
             thetimenow         
    ----------------------------
     2013-03-05 18:45:11.127092
     2013-09-07 16:43:01.349823
     2013-03-05 18:53:35.888306
     2013-09-07 16:53:06.553129
     2013-10-29 00:38:56.909418
    (5 rows)
    
    
    =# select created_at as "theTimeNow" from users limit 5;
             theTimeNow         
    ----------------------------
     2013-03-05 18:45:11.127092
     2013-09-07 16:43:01.349823
     2013-03-05 18:53:35.888306
     2013-09-07 16:53:06.553129
     2013-10-29 00:38:56.909418
    (5 rows)
    

    Notice the column name outputs