遍历数据库中的每条记录 - Ruby on Rails / ActiveRecord

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13442073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:02:30  来源:igfitidea点击:

Iterating through every record in a database - Ruby on Rails / ActiveRecord

ruby-on-railsdatabaseloopsrails-activerecord

提问by dougiebuckets

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

n00b 问题。我正在尝试遍历数据库中的每个用户记录。伪代码可能看起来像这样:

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 :)

有人可以告诉我这样做的最佳方法吗?语法方面的一些帮助也会很棒:)

回答by Adrien Coquio

Here is the correct syntax to iterate over all User :

这是迭代所有 User 的正确语法:

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

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

要提高性能并减少负载,请使用User.find_each参见文档)而不是User.all. 请注意,使用find_each会失去排序的能力。

回答by Andres Ehrenpreis

Also a possible one-liner for same purpose:

还有一个可能的单线用于相同目的:

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