Agile Web Development with Rails Translator (17)

Source: Internet
Author: User
Tags error handling generator

Agile Web Development with Rails Translator (17)

Chapter Nineth Task D: Settlement!

So far, we have built a basic product management system, we implement a catalog and have a nice shopping cart. Now we need to get the buyer to actually buy something in the shopping cart. Before proceeding, let us implement the settlement function first.

We are not going to go too far. All we have to do now is get the user's contact details and payment methods. Using these we will build an order in the database. Along it we can look more at model, confirm, form processing, and components.

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

Joe asked ...

where is the credit card handled?

At this point, our tutorial application is somewhat detached from the fact. In reality, we may need our application to handle commercial payments. We may even want to integrate credit card processing (perhaps using the payment module). However, the integration of a payment processing system requires a lot of people to work and work from start to finish. This shifts our attention to rails, so we continue this incomplete practice.

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

9.1 Iteration D1: Capturing orders

An order is a group of item items, with the details of the purchase transaction. We already have a product project-we've defined them when we created the shopping cart in the previous chapter. We don't have a table for saving orders yet. Based on a 47-page chart, and after a simple communication with the customer, we can create an Orders table.

CREATE TABLE Orders (

ID int NOT NULL auto_increment,

Name varchar (+) is not NULL,

Email varchar (255) NOT NULL,

Address text NOT NULL,

Pay_type Char (TEN) is not NULL,

Primary KEY (ID)

);

We know that when we create a new order, it is bound to be associated with one or more item items. In database terminology, this means that we need to add a foreign key reference from the Line_items table to the Orders table, so we take this opportunity to also update the DDL of line items (see the 487-page Create.sql list to see how to add the drop TABLE statement.) )

CREATE TABLE Line_items (

ID int NOT NULL auto_increment,

product_id int NOT NULL,

order_id int NOT NULL,

Quantity int NOT null default 0,

Unit_price Decimal (10,2) is not NULL,

Constraint fk_items_product foreign KEY (product_id) references products (ID),

Constraint Fk_items_order foreign KEY (order_id) references orders (ID),

Primary KEY (ID)

);

Remember to update the program (which clears all the data contained in your database) and use the rails generator to create the order model. We didn't regenerate the line items model, because this is good.

depot> MySQL depot_development <db/create.sql

depot> Ruby Script/generate Model Order

This tells the database the foreign key thing. This is a good thing because many databases will check the foreign key constraints to keep our code correct. But we also have to tell rails that there are many items for an order, and that a commodity item belongs to an order. First, we open the newly created ORDER.RB file in the App/models directory and add a call to Has_many ().

Class Order < ActiveRecord::Base

Has_many:line_items

End

Below, we specify a reverse link to add the call to the Belongs_to () method in the Line_item.rb file (remember that when we set up the cart, a line item was declared to belong to a product.) )

Class LineItem < ActiveRecord::Base

Belongs_to:p roduct

Belongs_to:order

# . . .

We also need an action to process the get order details. In the previous chapter we set up a link to the action called Checkout in the cart view, so now we have to implement a checkout () method in the store controller.

def checkout

@cart = Find_cart

@items = @cart. Items

If @items. Empty?

Redirect_to_index ("There ' s nothing in your cart!")

Else

@order = Order.new

End

End

Notice how we first check to make sure there is something in the shopping cart. This prevents people from navigating directly through the payment operation and creating an empty order.

Assuming we already have a valid cart, we create a new Order object to populate the view. Note that this order has not yet been saved to the database-it just uses view to assemble the checkout form.

Checkout view is within the checkout.rhtml file in the App/views/store directory. Let's build something simple to show how to relate the form data to the rails model object. Then we add confirmation and error handling, and for rails, starting with basics and repetition helps make things easier.

Rails and Forms

Rails provides powerful support for getting data from a relational database and passing it into a Ruby object. So you also expect to pass data between the model object and the user's browser, and it has the same support.

We have seen this example. When we create our product management controller, we use scaffold generator to create a form to get all the data for a new product. If you look at that view's code (app/views/admin/new.rhtml), you'll see the following:

<%= start_form_tag:action = ' Create '%>

<%= render_partial "Form"%>

<%= Submit_tag "Create"%>

<%= End_form_tag%>

<%= link_to ' back ': action = ' list '%>

This involves using a render_partial (' form ') sub-form. [Render_partial () is a deprecated form of render (:p artial=> ...). The scaffold generators had not been updated to create code using the-the-newer form at the time this book was written.] This sub-form in file _form.rhtml gets information about the product:

<%= error_messages_for ' product '%>

<!--[form:product]-->

<p><label for= "Product_title" >Title</label><br/>

<%= Text_field ' product ', ' title '%></p>

<p><label for= "Product_description" >Description</label><br/>

<%= text_area ' product ', ' description ',: rows = 5%></p>

<p><label for= "Product_image_url" >image url</label><br/>

<%= Text_field ' product ', ' Image_url '%></p>

<p><label for= "Product_price" >Price</label><br/>

<%= Text_field ' product ', ' price '%></p>

<p><label for= "product_date_available" >date available</label><br/>

<%= datetime_select ' product ', ' date_available '%></p>

<!--[eoform:product]-->

We can also use scaffold generator to create a form for the Orders table, but the form that rails generates is not always so beautiful. We're going to build something nicer. Let's learn more about how to automatically generate forms before we create our own data entry forms.

Rails has a corresponding model-dependent helper method for all of the standard HTML input tags. For example, we need to create a html<input> tag to allow buyers to enter their names. In rails, we can write the following statement in view:

<%= Text_field ("Order", "name",: size = +)%>

Here, Text_field () will create an HTML <input> tag with type= "text". This statement assembles that field with the contents of the Name field within the @order model. Even when the end user submits the form last, model is able to get the new value that the browser responds to the field, save it, and write to the database when needed.

There are many helper methods for forms (which we'll discuss in more detail on page 332). In addition to Text_field (), we can use Text_area () to get the buyer's address, and select () to create a choice list of payment methods.

Of course, in order for rails to get a response from the browser, we need to link the form to the rails action. We can do this by specifying a link to our Application,controller, and the <form> tag's action within the Action=attribute. But using the Form_tag () method is easier, and another rails helper method does the same thing.

So, with these background information, we're ready to create a view that gets the order information. Let's try the checkout.rhtml file in the App/views/store directory first.

<% @page_title = "Checkout"-%>

<%= Start_form_tag (: action = "Save_order")%>

<table>

<tr>

<td>Name:</td>

<td><%= Text_field ("Order", "name", "size" = +)%></td>

</tr>

<tr>

<td>EMail:</td>

<td><%= Text_field ("Order", "email", "size" = +)%></td>

</tr>

<TR valign= "Top" >

<td>Address:</td>

<td><%= Text_area ("Order", "Address", "cols", "Rows" = 5)%></td>

</tr>

<tr>

<td>pay using:</td>

<td><%=

options = [["Select a payment Option", ""]] + Order::P ayment_types

Select ("Order", "Pay_type", options)

%></td>

</tr>

<tr>

<td></td>

<td><%= Submit_tag ("CHECKOUT")%></td>

</tr>

</table>

<%= End_form_tag%>


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.