• No se han encontrado resultados

Competencias Profesionales Competencias Sociales

5 MARCO TEORICO CONCEPTUAL

We’re looking at sessions because we need somewhere to keep our shopping cart. We’ve got the session stuff sorted out, so let’s move on to implement the cart. For now, let’s keep it simple. It holds data and contains some business logic, so we know that it is logically a model. But, do we need acartdatabase table? Not necessarily. The cart is tied to the buyer’s session, and as long as that session data is available across all our servers (when we finally deploy in a multiserver environment), that’s probably good enough. So for now we’ll assume the cart is a regular class and see what happens. We’ll use our editor to create the file cart.rb in the app/models directory.1 The implementation is simple. The cart is basically a wrapper for an array of items. When a product is added (using theadd_productmethod), it is appended to the item list.

Download depot_f/app/models/cart.rb

class Cart attr_reader

֒→page635 attr_reader :items

def initialize @items = [] end

1. Note that we don’t use the Rails model generator to create this file. The generator is used only to create database-backed models.

def add_product(product) @items << product end

end

Observant readers (yes, that’s all of you) will have noticed that our catalog listing view already includes an Add to Cart button for each product.

Download depot_f/app/views/store/index.rhtml

<%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>

This button links back to an add_to_cart action in the store controller (and we haven’t written that action yet). It will pass in the product id as a form parameter.2 Here’s where we start to see how important the idfield is in our models. Rails identifies model objects (and the corresponding database rows) by theiridfields. If we pass an id toadd_to_cart, we’re uniquely identifying the product to add.

Let’s implement the add_to_cart method now. It needs to find the shopping cart for the current session (creating one if there isn’t one there already), add the selected product to that cart, and display the cart contents. So, rather than worry too much about the details, let’s just write the code at this level of abstraction. Here’s theadd_to_cartmethod inapp/controllers/store_controller.rb.

Download depot_f/app/controllers/store_controller.rb

Line 1 def add_to_cart

- @cart = find_cart

- product = Product.find(params[:id]) - @cart.add_product(product)

5 end

On line 2 we use thefind_cart method we implemented on the preceding page to find (or create) a cart in the session. The next line uses theparamsobject to get theidparameter from the request and then calls theProductmodel to find the product with that id. Line 4 then adds this product to the cart.

The params object is important inside Rails applications. It holds all of the parameters passed in a browser request. By convention, params[:id]holds the id, or the primary key, of the object to be used by an action. We set that id when we used:id => productin thebutton_tocall in our view.

Be careful when you add theadd_to_cartmethod to the controller. Because it is called as an action, it must be public and so must be addedabovetheprivate directive we put in to hide thefind_cartmethod.

What happens when we click one of the Add to Cart buttons in our browser? 2. Saying:id => productis idiomatic shorthand for:id => product.id. Both pass the product’s id back to the controller.

What does Rails do after it finishes executing the add_to_cart action? It goes and finds a template called add_to_cart in the app/views/store directory. We haven’t written one, so Rails complains. Let’s make it happy by writing a trivial template (we’ll tart it up in a minute).

Download depot_f/app/views/store/add_to_cart.rhtml

<h1>Your Pragmatic Cart</h1> <ul>

<% for item in @cart.items %> <li><%= h(item.title) %></li> <% end %>

</ul>

So, with everything plumbed together, let’s hit Refresh in our browser. Your browser will probably warn you that you’re about to submit form data again (because we added the product to our cart using button_to, and that uses a form). Click OK, and you should see our simple view displayed.

There are two products in the cart because we submitted the form twice (once when we did it initially and got the error about the missing view and the second time when we reloaded that page after implementing the view).

Go back tohttp://localhost:3000/store, the main catalog page, and add a different product to the cart. You’ll see the original two entries plus our new item in your cart. It looks like we’ve got sessions working. It’s time to show our customer, so we call her over and proudly display our handsome new cart. Somewhat to

our dismay, she makes thattsk-tsk sound that customers make just before telling you that you clearly don’t get something.

Real shopping carts, she explains, don’t show separate lines for two of the same product. Instead, they show the product line once with a quantity of 2. Looks like we’re lined up for our next iteration.

Documento similar