Fleeting Thoughts

For anything greater than 140 characters...

Jul 4

Rails Part 3: Creating a Cart

Had a bit of an absolute nightmare here - one of those ‘oh yeah, I think I’ve followed the code carefully, but…’ moments. Just couldn’t get the darned thing to run without errors

Eventually decided that the only way I was going to make progress was by (sadly) trashing my earlier code and stepping through the sample PragProg code provided on their website… a clash of Rails versions later (2.3.5 versus 2.2.2 - resolvable via the environment.rb file) and we’re back up and running…phew!

Creating a cart showed me how to create user sessions on the database using the rake db:sessions:create command (and then migrating the new DB code). I also created a cart as a class (strictly, a ‘Cart’, I suppose) and learnt about the use of attr_reader to make properties of my class available to the system. I defined a couple of methods in the class and learnt how to call them from a button that was defined in the index.html.erb view.

I went through a couple of iterations to ‘smarten up’ the cart (mainly by introducing a CartItem class) and made sure that users would see a clean display of their chosen items.

I learnt some error trapping using the Flash process as well as controlling error flow with redirect_to :action => ‘index’. The errors were displayed nicely by further fiddling with the CSS. 

Finally, I added functionality to ‘empty’ the cart in several places (add_to_cart.html.erb and store_controller.rb). Again - pretty easy, just a button of the form:

<%= button_to ‘Empty Cart’, :action => ‘empty_cart’ %>

and the appropriate 

def empty_cart

end

definition in the store_controller…nice!

Hopefully - back on track…just in time for the Ajax-ification of the website in the next installment!


  1. nickjewell posted this