6

Let's say I have a table World.

I have a field called foo within the table. I want to query the World table and select foo, but I would like to alias it as bar in the subsequent conversion to JSON output.

Is there any way to alias the field name for just this one ActiveRecord query? Not looking to alias the field through the entire application.

Viet
  • 3,257
  • 3
  • 28
  • 36
  • Just to comment. I was aliasing just like how Mori outlined before I posted this question. It didn't work for me because the alias I was choosing conflicted with the a gem I had associated to the application (Paperclip). Example: I was trying to alias image_file_name to image. But due to what I think is Paperclip's doing, I couldn't use the image alias. Changing it to something else, like img, worked. – Viet Jun 03 '13 at 23:30

3 Answers3

18

Just use the SQL alias feature in a select method call:

w = World.select("foo as bar").first
w.bar # returns value for foo
w.foo # ActiveModel::MissingAttributeError
Mori
  • 27,279
  • 10
  • 68
  • 73
2

I avoid writing SQL as much as I can, so I would rather use ARel to build the query. Something like

World.select(World.arel_table['foo'].as('bar'))

Using some syntactic sugar, it's just:

at = World.arel_table
World.select(at['foo'].as('bar'))
akim
  • 8,255
  • 3
  • 44
  • 60
0

You can override to_json method in yours World model. Check details on how to do that here How to override to_json in Rails?

Community
  • 1
  • 1
Sergey Kuznetsov
  • 8,591
  • 4
  • 25
  • 22