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 :)
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.
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.
Also a possible one-liner for same purpose:
User.all.map { |u| u.number = ""; puts u.number }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With