[LRUG] Updating activerecord associations without saving

Anthony Eden anthonyeden at gmail.com
Thu Sep 23 06:39:22 PDT 2010


You could store the associated record as a simple instance variable on the
model.

Alternatively maybe the fact that someone is trying on the underwear before
buying it *is* something you want to keep track of, just through another
association?

Sincerely,
Anthony Eden

On Thu, Sep 23, 2010 at 3:34 PM, Tim Cowlishaw <tim at timcowlishaw.co.uk>wrote:

> 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
>
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>



-- 
GMU/IT d- s: a33 C++(++++)$ UL@ P--- L+(++) !E W+++$ !N o? K? w--- !O M++ V
PS+ PE Y PGP t+ !5 X- R tv b++ DI+ D++ G- e++ h---- r+++ y++++**

http://anthony.mp
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20100923/103cc4cf/attachment-0003.html>


More information about the Chat mailing list