rails update_all fields and increment count by 1

4.1k views Asked by At

I have a column in my mysql table called download_count of type int.

Now I want to use update_all to update some fields with some values, but also increment the download_count along with it.

I have tried the following syntax:

find_record.update_all(username: username, download_date: download_date, "download_count= download_count + 1")

But I beleive the above acts like a where clause. So the download_count does not get updated. I want the username, download_date and the download_count to be updated by the above query.

Can someone point me to the correct syntax?

2

There are 2 answers

0
Arup Rakshit On BEST ANSWER

Another way, which wouldn't by pass the validations and callbacks.

User.find_each do |u| 
  u.update_attributes(
                      username: username, 
                      download_date: download_date, 
                      download_count: u.download_count + 1
                     )
end

Read the documentation of this find_each method to know why it is efficient. I took, User as a example name of a model; you use your one.

2
usha On

Try

find_record.update_all(["username=?, download_date=?, download_count=download_count+1", username, download_date])

Second argument to update_all is a condition.