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.
The WHERE clause can contain non-correlated aliases and correlated aliases.
Column aliases can be used with GROUP BY and ORDER BY clauses. We cannot use a column alias with WHERE and HAVING clauses.
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.
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.
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
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With