0

I have a User model with fields name, age(in years) and dob(ie date of birth). I want to update all the users age by calculating the difference between dob and Date.today. I want it done in a single query rather than updating each single user.

The code that i am trying to use is:

User.update_all("age = ?", Date.today - :dob); #not working

how can i fix it? I am using Active Record.

-----UPDATE

After much trying i managed to get it done as but since its pure mysql query. How can it be done through ORM?

User.update_all("age = floor(datediff(curdate(), dob) / 365.25);")
Prasad Surase
  • 6,486
  • 6
  • 39
  • 58
  • Which database adapter are you using? – Pavan Jun 12 '14 at 12:27
  • 1
    possible duplicate of [How to update thousands of records](http://stackoverflow.com/questions/22608912/how-to-update-thousands-of-records) – Pavan Jun 12 '14 at 12:46
  • @Pavan I can get it done using mysql query similar to the answer in the link that you have provided in the comment. I want to know if it can be done using ActiveRecord. – Prasad Surase Jun 12 '14 at 12:48
  • If you have found the answer to your question, please post is as an answer rather than an update. It helps everyone. :) – Aravind Jun 12 '14 at 13:21
  • @Aravind I did find the answer and its posted in the question but unfortunately, it contains some sql code. I am looking for solution using no sql but RoR. – Prasad Surase Jun 13 '14 at 03:57

0 Answers0