[LRUG] Updating activerecord associations without saving

Tim Cowlishaw tim at timcowlishaw.co.uk
Thu Sep 23 06:34:09 PDT 2010


Hi all,

Could I pick your collective brains about a little activerecord issue I'm having?

Let's say you have two AR models:

class Person < ActiveRecord::Base
	has_one :underpants
end

Underpants < ActiveRecord::Base
	belongs_to :person
end

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

person.underpants = boxers
person.save

Now, my app  allows people to test out underpants before they commit to them, so I want to set the underpants association on person, and keep the updated person in memory, without that change hitting the database until I explicitly save.

But
person.underpants = yfronts

immediately updates the foreign key in the database. I can see why this happens - as the foreign key for the association is on my underpants table, it wouldn't be updated on hitting 'save' on the person, so it's done eagerly. However, is there any way to avoid this happening, and deal with the consequences myself?

tl;dr: can I set a has_one association on an activerecord object in memory only, without touching the DB?

Cheers.

Tim





More information about the Chat mailing list