Rails: Keep changes to objects/associations in memory without saving to database
I have a Rails model with various attributes and has_many relationships to other models. In the view I want the user to be able to enter/change values which will change the values in the loaded object and return results calculated from them whenever they make a change. However, I don't want the values to change in the database until they select 'Save'. The problem I'm running into is that the variables I associate with the collections pull from the database after each new change. So if I use something like the following:
@model.at开发者_运维百科tributes = params[:model]
it lasts the length of that particular call to the model, but the next time the user makes a change the collection is reloaded, losing all the previous changes aside from the most recent one. I've tried using an instance variable, e.g.:
@costs ||= self.costs
But whenever I run an operation on it, it reloads from the database, overwriting previous changes. E.g.
@costs[i].monthly = 10
Is there any way to ensure that changes persist across the session without saving to the database? Right now it's looking like my best option may be to create a separate model to store the values in and then save them back to the original when the user is finished.
You could either resave it to the params
hash whenever you make a change, or try using the session
hash (but you'll have to remember to clear it).
http://guides.rubyonrails.org/security.html#what-are-sessions
In short, data does not persist between requests. At the time I was under the impression that attributes held values for the length of the session. I've since learned that the only things that persist are the values stored in the database and those passed back and forth in the params and session hashes.
精彩评论