1

Is there a trick required to make Rails recognize constants in a SQL select statement? For example, the following SQL statement is valid:

SELECT id, name, 1 AS constant FROM table_name

And I would expect the results to have three columns returned: id, name and constant. The value in the constant column would always be 1.

However, in Rails if I try to do the same thing the constant column gets dropped using Model.find_by_sql:

TableName.find_by_sql("SELECT id, name, 1 AS constant FROM table_name")

or

ActiveRecord::Base.connection.execute("SELECT id, name, 1 AS constant FROM table_name")

Is this is a bug or a known limitation in Rails 4.0 or if there is another way to do this that I'm not trying?

0

1 Answer 1

1

What makes you think your constant isn't there? From the fine manual:

find_by_sql(sql, binds = [])
[...]
If you call a complicated SQL query which spans multiple tables the columns specified by the SELECT will be attributes of the model, whether or not they are columns of the corresponding table.

Emphasis mine. So if you say this:

a = TableName.find_by_sql("SELECT id, name, 1 AS constant FROM table_name")

then you can say a.first.constant and get something back. Note that the usual inspect output that you're probably looking at in the console won't include constant as AR's inspect only knows about table columns; you'll see things like this in the console:

[#<TableName id: 6, name: "Pancakes">, ...]

but the objects will respond to constant calls with '1's; yes, they'll probably be strings, you'll have to sort out the type conversions yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, sorry for the late reply. I wasn't explicitly looking for the constant in the results so I didn't know it was there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.