Is it possible to temporary cache an attribute's value in memory or do something similar?

Hello,

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?

Thanks,

Matthew

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?

Well if things do need to be atomic then you probably want to wrap this in a transaction and roll back if one of those validations fail. You could also change your conditions on that find to exclude a bar with a particular id

Fred