ddavison
ddavison

Reputation: 29032

Update ActiveRecord attribute with SQL function

In rails, are you able to update a record's attribute with an evaluation of a SQL function?

MySQL Table

| time_started        | time_to_execute |
|---------------------------------------|
| 2015-10-28 14:13:58 |      NULL       |

What I am trying to do:

update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))

through a model.


I've tried to do this using the common attribute update methods to no avail.

c.update_attribute(:time_to_execute, 'TIME_TO_SEC(TIMEDIFF(NOW(), time_started))')
c.update({:time_to_execute => 'TIME_TO_SEC(TIMEDIFF(NOW(), time_started))'})

Is it possible to update attributes of an ActiveRecord model using SQL functions?

I know that I can accomplish this executing arbitrary SQL, or calculating diff between two DateTime ruby objects, but I'm wondering if this is possible via a model method.

Upvotes: 2

Views: 1975

Answers (1)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

You can use #update_all to do this

c.class.where(id: c.id).update_all("time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started))")

Note that you can replace c.class with the actual class name of your model (not currently shown in the answer).

Update to show raw SQL implementation

c.class.connection.execute "update table set time_to_execute = TIME_TO_SEC(TIMEDIFF(NOW(), time_started)) WHERE id = #{ c.id }"

Upvotes: 6

Related Questions