So I had a functional Model, Controller, and View. My application loaded some rows from the database, performed some string manipulation / parsing, and handed them off to the View, which using CSS, formatted them for the screen. These rows from the database represented the lottery picks from the office pool. Now, I wanted to be able to enter the lottery draw for that day and check it against the picks.
I did some research and found out about “form helpers” and was able to create a single text field form, and that in turn was able to pass the contents to the Controller. It seemed logical to me not to want to re-use the same view and objects created when the form is initially displayed, and this is where I ran into some conceptual stumbling blocks. You see, I thought that once I’d populated a Model instance with data, and I was operating within the context of the same Controller, that the data would still be available. But in reality all of the data that had been retrieved from the database vanished when I submitted the form and called a method from the same Controller. I couldn’t see where I was going wrong. Was it a scope issue? It was time to “phone a friend”.
My friend explained to me that this being a web application, it ran under different rules to the way I was used to. It was stateless. Whatever had happened in previous executions was not carried over to the subsequent ones. Now, I’d done some ASP and JSP, and even PHP programming and I knew that you could create variables that persisted, so why couldn’t do that here? He explained that it was possible, but it wasn’t a good practice, and it went against many of the design paradigms. So to fix my “vanishing data” problem, I’d have to re-query the database every time the page was displayed. This seemed like a terrible inefficiency, I’d need to make an SQL query all the time. Actually, it wouldn’t be as bad as I was making out, cached queries would be make it all quite efficient, but I still had a hard time reconciling the fact that I would be involving a database call when I already had those returned rows available. Oh well.
It was quite easy to re-jig things in the Controller to repeat the database query, and once I did that the application started working as intended. I could go to the page, which would display the lottery picks. I could enter the draw for that day and the display would alter color and format to show the matching numbers.