Ruby on Rails: temporarily update an attribute into cache without saving it?
Posted
by randombits
on Stack Overflow
See other posts from Stack Overflow
or by randombits
Published on 2010-06-01T22:54:43Z
Indexed on
2010/06/01
23:23 UTC
Read the original article
Hit count: 137
I have a bit of code that depicts this hypothetical setup below. A class Foo which contains many Bars. Bar belongs to one and only one Foo. At some point, Foo can do a finite loop that lapses 2+ iterations. In that loop, something like the following happens:
bar = Bar.find_where_in_use_is_zero
bar.in_use = 1
Basically what find_where_in_use_is_zero does something like this in as far as SQL goes:
SELECT * from bars WHERE in_use = 0
Now the problem I'm facing is that I cannot run the following line of code after bar.in_use =1 is invoked:
bar.save
The reason is clear, I'm still looping and the new Foo hasn't been created, so we don't have a foo_id to put into bars.foo_id. Even if I set to allow foo_id to be NULL, we have a problem where one of the bars can fail validation and the existing one was saved to the database. In my application, that doesn't work. The entire request is atomic, either all succeeds or fails together. What happens next, is that in my loop, I have the potential to select the same exact bar that I did on a previous iteration of the loop since the in_use flag will not be set to 1 until @foo.save is called.
Is there anyway to work around this condition and temporarily set the in_use attribute to 1 for subsequent iterations of the loop so that I retrieve an available bar instance?
© Stack Overflow or respective owner