difference between find and find_by when modifying a record in-memory

Viewed 233

Say I have these two classes

class Gadget < ActiveRecord::Base
  has_many :widgets
end

class Widget < ActiveRecord::Base
  belongs_to :gadget
  # table has string attribute .color
end

And let's say that the database contains one gadget and one widget, each with id = 1, and the widget has a color of nil.

Modifying a record retrieved with .find

g = Gadget.first
w = g.widgets.find { |widg| widg.id == 1 }
w.color = "blue"
g.widgets.first.color
=> "blue"

Modifying a record retrieved with .find_by

g = Gadget.first
w = g.widgets.find_by(id: 1)
w.color = "blue"
g.widgets.first.color
=> nil

I can't account for this difference.

1 Answers

If you use find_by method, rails add that find_by statement to the end of the query so there will be only one record loaded to the memory (if there is) and the DB is here to find that record. If you use find method with a block, rails will first load all the widgets to the memory then it will search for a specific one for the given statement which will cause extra memory usage since DB can do the same job. Also if you use the find method like this: g.widgets.find(1) this will do same as the g.widgets.find_by(id: 1) method.

Related