Wes Creations
Wes Creations

Reputation: 387

How do I loop through a model and save that to an array?

I have a mailer that checks for all users that meet a certain criteria.

If that criteria is true, I'm trying to do a do loop, and return the result into an array.

I'm then trying to use that to loop through that array and send an email to each email in the array.

I tried assigning the variable 'emails' to this array where I'm passing this code in

emails = [User.where(:state => 'Arizona').each]

Which isn't working because when I do the following.. the emails aren't sent

    emails.each do |email|
      new_request(email,row).deliver_now
    end

Then I tried to do a loop and save those results to an variable

    User.where(:state => 'Arizona').each do |u|
     emails = u.email
    end

Yet again, when I do this following code the emails aren't sent

    emails.each do |email|
      new_request(email,row).deliver_now
    end

FYI - everything else is working just fine with the rest of my program, the emails are definitely going out fine when I don't use this code. For instance, if I do this:

emails = ['[email protected]','[email protected]']

the array works fine, and then I can do this..

    emails.each do |email|
      new_request(email,row).deliver_now
    end

and the code email is sent to [email protected] and [email protected]. So again, the real question is, how do I loop through those users where that criteria is true, and save to an array like this so I can run this emails.each do code and get it work?

Upvotes: 0

Views: 158

Answers (2)

Gregory Ostermayr
Gregory Ostermayr

Reputation: 1121

Just use pluck

User.where(:state => 'Arizona').pluck(:email)
=>  ["[email protected]", "[email protected]"]

Upvotes: 3

Aarthi
Aarthi

Reputation: 1521

  User.where(:state => 'Arizona').each do |u|
     emails = u.email
  end

In the above logic, in every iteration, the emails will be overwritten with the iteration email.

You have to insert the emails in an array to make the logic as expected.

emails = []
User.where(state: 'Arizona').each do |u|
  emails << u.email # To insert the user email into the array
end

You can also try to debug the values in the array whenever you face issues in logic.

   User.where(:state => 'Arizona').each do |u|
      emails = u.email
      p emails, "emails" # To check the value stored in the emails.
   end

Upvotes: 3

Related Questions