[LRUG] Updating activerecord associations without saving

Tom Stuart tom at experthuman.com
Thu Sep 23 07:03:47 PDT 2010


Hi Tim,

On 23 Sep 2010, at 14:34, Tim Cowlishaw wrote:
> tl;dr: can I set a has_one association on an activerecord object in memory only, without touching the DB?

One potential solution comes courtesy of LRUG's very own Murray Steele in the form of :inverse_of.

The problem is that you're assigning to a has_one and triggering behaviour that you don't want. So you could work around by saying:

  class Underpants < ActiveRecord::Base
    belongs_to :person, :inverse_of => :underpants
  end

And then you can just work with the other end of the association, without incurring the wrath of has_one assignments:

  person = Person.create
  yfronts = Underpants.create
  boxers = Underpants.create

  yfronts.person = person
  yfronts.person.underpants # == yfronts
  Person.first.underpants # == nil

tl;dr: :inverse_of lets you traverse the underpants association of the in-memory Person object without having saved anything to the database.

Cheers,
-Tom


More information about the Chat mailing list