开发者

Ruby on Rails: temporarily update an attribute into cache without saving it?

开发者 https://www.devze.com 2023-01-02 10:44 出处:网络
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+ itera

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?


You could save the bar with a null for foo_id

Or, can you keep a hash with the bar id and the value of in_use that is valid? Then you check for the value from the hash first, then from your bar object.

If you can't save the state to the db you have to do it outside the db. No one can tell you how to do that exactly without knowing the details of your project.

0

精彩评论

暂无评论...
验证码 换一张
取 消