Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4623

Ruby on Rails #find_each and #each. is this bad practice?

$
0
0

I know that find_each has been designed to consume smaller memory than each.I found some code that other people wrote long ago. and I think that it's wrong.

Think about this codes.

 users = User.where(:active => false) # What this line does actually? Nothing? users.find_each do |user|  # update or do something..  user.update(:do_something => "yes") end

in this case, It will store all user objects to the users variable. so we already populated the full amount of memory space. There is no point using find_each later on.

Am I correct?

so in other words, If you want to use find_each, you always need to use it with ActiveRecord::Relation object. Like this.

User.where(:active => false).find_each do |user|  # do something...end

What do you think guys?


Update

in users = User.where(:active => false) line,

Some developer insists that rails never execute query unless we don't do anything with that variable.What if we have a class with initialize method that has query?

class Test  def initialize    @users = User.where(:active => true)  end  def do_something    @user.find_each do |user|      # do something really..    end  endend

If we call Test.new, what would happen? Nothing will happen?


Viewing all articles
Browse latest Browse all 4623

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>