Rails ignores constants in SQL SELECT statement

后端 未结 1 1527
夕颜
夕颜 2021-01-25 12:14

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          


        
相关标签:
1条回答
  • 2021-01-25 12:32

    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.

    0 讨论(0)
提交回复
热议问题