36

n00b question. I'm trying to loop through every User record in my database. The pseudo code might look a little something like this:

def send_notifications

        render :nothing => true

        # Randomly select Message record from DB
        @message = Message.offset(rand(Message.count)).first

        random_message = @message.content

        @user = User.all.entries.each do
            @user = User.find(:id)

            number_to_text = ""

            @user.number = number_to_text #number is a User's phone number
            puts @user.number

        end

    end

Can someone fill me in on the best approach for doing this? A little help with the syntax would be great too :)

4
  • 1
    can we get a bit more background on what you are trying to achieve. Going through you user database this way seems a bit overhead Commented Nov 18, 2012 at 16:35
  • It's better if you get a basic knowledge in Ruby. You will not regret it , for sure . Anyway , tell us what is the purpose if the loop ? Commented Nov 18, 2012 at 16:40
  • Sending an SMS to every user in the the DB. 'number' = a User's phone number. Commented Nov 18, 2012 at 16:45
  • 1
    updated the post with all of the controller's code to give more context. Commented Nov 18, 2012 at 17:15

2 Answers 2

84

Here is the correct syntax to iterate over all User :

User.all.each do |user|
  #the code here is called once for each user
  # user is accessible by 'user' variable

  # WARNING: User.all performs poorly with large datasets
end

To improve performance and decrease load, use User.find_each (see doc) instead of User.all. Note that using find_each loses the ability to sort.

Sign up to request clarification or add additional context in comments.

Comments

1

Also a possible one-liner for same purpose:

User.all.map { |u| u.number = ""; puts u.number }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.