Search code examples
rubymodelupdate-attributes

How to update value of a Model's attribute in a for loop


I have the following code which works finde

twt = Tweet.where(user_id: @user.uid).where(status_id: 0).order(:created_at, :id).first
            twt.status_id = 1
            twt.save

I the want to make this code run for every user available in the database:

@user = User.all
            @user.each do |u|
            twt = Tweet.where(user_id: u.uid).where(status_id: 0).order(:created_at, :id).first
            twt.status_id = 1
            twt.save
            end

this however gives me the error:

undefined method `status_id=' for nil:NilClass

why is there no class found? Why wasn't it set correctly in twt?


Solution

  • Simply, for some user, this line

    twt = Tweet.where(user_id: u.uid).where(status_id: 0).order(:created_at, :id).first
    

    found no results. You could add

    if twt
      twt.status_id = 1
      twt.save
    end
    

    Anyway, you can rewrite that as

    Tweet.find_by(user_id: u.uid, status_id: 0).order(:created_at, :id)
    

    Obviously, it's possible to do all this job in just one SQL query.