本文介绍了遍历数据库中的每个记录-Ruby on Rails/ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
n00b问题.我试图遍历数据库中的每个用户记录.伪代码可能看起来像这样:
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 :)
推荐答案
这是遍历所有User的正确语法:
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
end
要提高性能并减少负载,请使用User.find_each
(请参阅doc ),而不是User.all
.请注意,使用find_each
会失去排序的能力.
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.
这篇关于遍历数据库中的每个记录-Ruby on Rails/ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!