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

60 Views Asked by At

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?

1

There are 1 best solutions below

3
Ursus On BEST ANSWER

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.