Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord query alias field name output

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.

like image 438
Viet Avatar asked Jun 03 '13 19:06

Viet


People also ask

Can we use alias name in WHERE condition?

The WHERE clause can contain non-correlated aliases and correlated aliases.

Can we use alias column name in WHERE clause?

Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.

Can you use alias in WHERE clause SQL?

In PROC SQL, a column alias can be used in a WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause. In the ANSI SQL standard and ISO SQL standard, the value that is associated with a column alias does not need to be available until the ORDER BY clause is executed.

When creating a query what is the purpose of including a column alias?

The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular SQL query.


2 Answers

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
like image 74
Mori Avatar answered Nov 14 '22 23:11

Mori


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'))
like image 38
akim Avatar answered Nov 15 '22 01:11

akim