Beengie
Beengie

Reputation: 1608

Rails access calculated field

I have a model "Job" that has 2 fields in it :id and :qty, I can't seem to access a calculated field in a query. What am I doing wrong?

Job.select("*, (qty * 2) AS TEST")

Upvotes: 1

Views: 254

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

You can access the aliased column this way:

Job.select("*, (qty * 2) AS double_qty").first.double_qty

(test is a private method of Rails and you should avoid using it as an aliased column)

To use it in an order clause:

scope :ordered, -> { select('*, (qty * 2) AS double_qty').order('double_qty DESC') }

Use it like this:

Job.ordered
# => should trigger a SQL query like: 
SELECT jobs.*, (qty * 2) AS double_qty 
ORDER BY double_qty DESC;

Upvotes: 1

Related Questions