Agile Web Development with Rails translations (18)

Source: Internet
Author: User

Agile Web Development with Rails translations (18)

Here, the only interesting thing is the code associated with the select list. We have assumed that the list of valid payment options is an attribute of order model-it will be an array of an array in the model file. The first element of each sub array is a string that is displayed as an option selected, and the second value is stored in the database. [If we expect non-rails applications to update the Orders table, we may want to move the payment type list to a separate table and refer a foreign key to the orders column to the new table.) In this environment, rails also provides good support for generating list listings. We'd better define this array of options in model ORDER.RB before we forget.

Payment_types = [

["Check", "Check"],

["Credit card", "CC"],

["Purchase Order", "PO"]

].freeze # Freeze to make this array constant

If there is no current option in model, we want to display some hint text in the input area of the browser. The options we return in model are beginning to add a new option to achieve this. This new option has a suitable display string and a null value.

After all this has been done, we can open the browser. To add some merchandise to the shopping cart, click on the Checkout link and you will see the new Payment page as shown in Figure 9.1:

It looks good. Of course, if you click on the Checkout button, you will be greeted with the following greetings:

Unknown Action

No Action responded to Save_order

Let's continue to implement the Save_order () action in the store controller.

The method must:

1. Capture a value from the form to assemble a new Order model object.

2. Add items to the order from our shopping cart.

3, confirm and save order. If it fails, display the appropriate information and let the user correct the problem.

4. Once the order is saved successfully, the catalog page is displayed again, including information confirming that an order has been saved.

The method ultimately looks like the following:

Line 1 def save_order

-@cart = Find_cart

-@order = Order.new (Params[:order])

-@order. Line_items << @cart. Items

5 if @order. Save

-@cart. empty!

-Redirect_to_index (' Thank for your order. ')

-Else

-Render (: Action => ' checkout ')

Ten End

-End

On line 3rd, we create a new Order object and initialize it with the form data. In this example, we want all of the form data to be related to the order object, so we chose an order hash table from the argument (we'll discuss how the form is connected to model on page 341). The next line adds the item that is already in the shopping cart to the order-the session data is still there after the last action is processed. Note that we do not need to do any special processing for the different foreign key fields, such as setting the ORDER_ID behavior in line item to create the newly created order lines. When we use the Has_many () and belongs_to () declarations (we add them separately to the order and LineItem model), rails automatically completes all of this.

Then line 5th, we tell the order object to save itself (as well as its children, commodity items) to the database. During this time, the order object will complete the validation confirmation (but we'll deal with it later). If the save succeeds, we empty the cart to prepare for the next order and display the catalog again. Use our Redirect_to_index () method to display a delightful message. Conversely, if the save fails, we display the checkout form again.

The last thing we did before we called the client, remember when we showed her our first product Management page. She asked us to increase our validity confirmation. We might as well do the same for our checkout pages. For now, we only check that each field in the order is given a value. We know how to do-Add a validates_presence_of () method to order model:

Validates_presence_of:name,: Email,: Address,:p Ay_type

----------------------------------------------------------

Joe asked ...

You do not create copies of orders.

Joe saw our controller in two actions, checkout and Save_order, and created the order model object, and he wondered why it didn't cause duplicates in the database. The answer is simple: The checkout action creates an order object in memory and simply passes it to the template code that works together. Once the response is sent to the browser, the special object is thrown away, and finally it is reclaimed by the Ruby garbage collector. It has never been exposed to a database.

The Save_order action also creates an order object, which is assembled from the form field. This object is saved in the database. So the model objects play two roles: they map data to and from the database, but they are also just normal objects that hold business data. When you typically invoke the Save () action, they affect the database.

---------------------------------------------------

So, for the first test, click the Checkout button without filling out any form fields. We want to see the checkout page appear again and give some error information about the blank field. Instead, we only see checkout pages-no error messages. We forgot to tell rails to write them. [If you ' re following along at home and your get the message No action responded to Save_order, it's possible that you added The Save_order () method is the private declaration in the controller. Private methods cannot be called as actions.]

Any errors related to validation or save model should be saved with the model. Here's another helper method, Error_messages_for (), which extracts and formats these errors in view. We just add one line to the beginning of the checkout.rhtml file.

<%= error_messages_for ("Order")%>

As with the validation of the Admin page, we need to add the SCAFFOLD.CSS style sheet to our store layout file to get the appropriate format for these errors.

<%= Stylesheet_link_tag "Scaffold", "Depot": Media => "All"%>

When we're done, submitting an empty checkout page will show us a lot of high brightness errors, as shown in Figure 9.2.

If we fill out some data, as shown in Figure 9.3, click Checkout, we should go back to the category page, as shown at the bottom of the chart. But did it work? Let's look at the database.

depot> MySQL Depot_development

Welcome to the MySQL Monitor. Commands End With; or G.

Mysql> select * from Orders;

+----+-------------+-----------------------+-------------+----------+

| ID | name | email | Address | Pay_type |

+----+-------------+-----------------------+-------------+----------+

| 3 | Dave Thomas | customer@pragprog.com |

+----+-------------+-----------------------+-------------+----------+

1 row in Set (0.00 sec)

Mysql> select * from Line_items;

+----+------------+----------+----------+------------+

| ID | product_id | order_id | Quantity | Unit_price |

+----+------------+----------+----------+------------+

| 4 | 4 | 3 | 1 | 29.95 |

+----+------------+----------+----------+------------+

1 row in Set (0.00 sec)

Saved. At least, now we can show it to our customers. She likes it, except ... Do you think we should add a summary of the contents of a shopping cart on the checkout page? It sounds as if we need a new repetitive process.

123 Main St| Check |

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.