Search code examples
mysqlruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

rails update_all fields and increment count by 1


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?


Solution

  • 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.