Question

I'm not quite sure how to use the select method when making SQL queries on rails. I'm quite familiar with the where clauses, order clauses, Boolean conditions etc... However, select has me a bit confused here's an example:

>> b = BillableWeek.select("mon_hrs + tues_hrs as two_day_total").first

What exactly is select doing here? And what is it's function in general?

In the above case, I'm guessing that it's selecting the column's mon_hrs & tues_hrs from the BillableWeek object, adding them and storing the result in two_day_total?

Is two_day_total also a column though?

Était-ce utile?

La solution

select method on ActiveReocrd classes override sql SELECT statement used to fetch records from db. The example you gave will execute the query:

SELECT mon_hrs + tues_hrs as two_day_total FROM billable_weeks LIMIT 1

It will return just one column (not really existing in the table), called two_day_total being a sum of vlueas stored in two real columns mon_hrs and tues_hrs.

Autres conseils

::select can do a lot of different queries. But I believe what you're doing is creating an alias method that can be called by ActiveRecord. Here's the example from the documentation.

#If an alias was specified, it will be accessible from the resulting objects:

Model.select('field AS field_one').first.field_one
# => "value"

It doesn't permanently add an actual column to your database since that would, in a sense, make migrations kind of pointless if we constantly add and remove columns with method calls. In short, your query adding the two values together and aliasing it is just making a shortcut for returning that value not a column.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top