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

笑着哭i 提交于 2019-12-09 05:04:22

问题


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


回答1:


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

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.




回答2:


Also a possible one-liner for same purpose:

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


来源:https://stackoverflow.com/questions/13442073/iterating-through-every-record-in-a-database-ruby-on-rails-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!