Dan Ott

Today I Learned — March 9, 2016

Rails will save associations by default. If you build an in-memory representation of a record that’s not intended to be saved with a call to update you need to do one of two things.

  1. Set autosave to false. Example: has_one :other_thing autosave: false.
  2. Don’t associate the built record with the object you’re saving

This default behavior manifested itself because I was doing something of the form:

class Thing
  has_one :other_thing # 1. Use autosave: false

  def optimistic_version_of_other_thing
    OtherThing.new(thing: self) # 2. don't associate the record with self
  end
end

thing = Thing.last
thing.optimistic_version_of_other # I don't want this persisted
thing.update(anything: "else")