Rails 3: Including SQL Function in a Query

MyModel.select('a, b, c').all

This returns the following from the database:

 +---+---+---+ | a | b | c | +---+---+---+ | 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 | +---+---+---+ 

Question: How to include the fourth column with the result of the SQL function?

i.e.

 +---+---+---+---------------------+ | a | b | c | MYFUNCTION(a, b, c) | +---+---+---+---------------------+ | 1 | 2 | 3 | 123 | | 4 | 5 | 6 | 456 | | 7 | 8 | 9 | 789 | +---+---+---+---------------------+ 

Failed to complete the following:

MyModel.select('a, b, c, MYFUNCTION(a, b, c)').all

although if I use AS to give the column the name of a valid model attribute, it works:

MyModel.select('a, b, MYFUNCTION(a, b, b) AS c').all

 +---+---+-----+ | a | b | c | +---+---+-----+ | 1 | 2 | 122 | | 4 | 5 | 455 | | 7 | 8 | 788 | +---+---+-----+ 

I would prefer to solve this in the context of the model, rather than returning to raw SQL, since I also need to use scopes.

Any suggestions that are very much appreciated.

+4
source share
1 answer

You can give an arbitrary name to an AS column, instead of specifying an existing attribute.

 irb(main):009:0> u = User.select('id, id+1 as blah').first => #<User id: 1> irb(main):010:0> u.id => 1 irb(main):011:0> u.blah => 2 irb(main):012:0> 
+2
source

Source: https://habr.com/ru/post/1336530/


All Articles