问题
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?
回答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.
来源:https://stackoverflow.com/questions/24131189/rails-ignores-constants-in-sql-select-statement