Alex Rivera | Logout

how does activerecord know to perform an insert or update?

Asked 2009-11-05T21:27:02.173
13

Maybe some Ruby experts out there can shed some light on how activerecord know to do an insert or update when calling save(). What is the logic behind it? Does it check to see if the primary key is blank or something and if so does an insert, if not an update?

Edit
Report

1 Answer

23

Whilst it's fine for some people to say "RTFM" I rather the more walk-through-but-still-entirely-useless-when-Rails-3-comes-out-and-changes-everything response:

How it works in Rails 2.3 (aka "today")

save calls create_or_update which looks like this:

def create_or_update
  raise ReadOnlyRecord if readonly?
  result = new_record? ? create : update
  result != false
end

You can ignore the first line of this method as it only raises an error if the record is readonly (it isn't usually, but in the case of joins it may be). What we are interested in here is the second and third lines inside the method.

The second line calls new_record? which is defined as this:

  # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet; otherwise, returns false.
  def new_record?
    @new_record || false
  end

And the variable @new_record is set when the initialize (new calls initialize, and gives us a new object, some background Ruby-fu here) method is called.

So if this @new_record is true it'll call create and if it's false it'll call answered 2009-11-06T03:31:27.487

Your Answer