[LRUG] Updating activerecord associations without saving
Tim Cowlishaw
tim at timcowlishaw.co.uk
Thu Sep 23 06:47:19 PDT 2010
On 23 Sep 2010, at 14:43, Anthony Green wrote:
>
> I usually use build in similar circumstances
>
> Person.build_underpants(:type => 'boxers')
>
Ok, this is exactly what I thought, but even using build, it's updating the foreign key on the underpants table (nulling it out) when i instaantiate the new underpants instance. It's absolutely madenning!
Chers,
Tim
>
> On 23/09/2010 14:34, "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
>
> --
> Anthony Green
>
>
>
>
>
>
> http://www.bbc.co.uk/
> This e-mail (and any attachments) is confidential and may contain personal views which are not the views of the BBC unless specifically stated.
> If you have received it in error, please delete it from your system.
> Do not use, copy or disclose the information in any way nor act in reliance on it and notify the sender immediately.
> Please note that the BBC monitors e-mails sent or received.
> Further communication will signify your consent to this.
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
More information about the Chat
mailing list