Use Ruby on Rails to quickly develop web applications.

Source: Internet
Author: User
Tags control label processing text

Use Ruby on Rails to quickly develop web applications.

Ruby on Rails is impacting the entire Web development field. Let's first understand the underlying technologies:

Ruby is a free, simple, intuitive, scalable, portable, and interpreted scripting language for fast and simple object-oriented programming. Similar to Perl, it supports many features for processing text files and executing system management tasks.
Rails is a complete open-source Web framework written in Ruby. It aims to use simpler and fewer code to write actually used applications.

As a complete framework, this means that all layers in Rails are constructed for collaborative work, so you don't have to repeat it yourself, you can use only one single language. In Rails, all content (from template to control flow to business logic) is written in Ruby. Rails supports reflection and runtime Extension Based on configuration files and annotations.

This article describes in detail the components of Rails and introduces its working principles.
Rails Introduction

The first thing you need to understand about Rails is its model/view/controller (model/view/controller, MVC) architecture. Although this technology is not unique to Rails-or even not unique to Web applications (compared to other programs), Rails has a very clear and specific MVC way of thinking. If you do not use the MVC method, Rails will be much less useful (compared to following its pattern ).

The model of the Rails application is mainly the underlying database it uses. In fact, in many cases, the Rails application is performing operations on the data in the relational database management system (RDBMS) in a managed way.

The ActiveRecord class is a core component of Rails. It maps Relational Tables into Ruby objects so that they can be operated by controllers and displayed in views. Rails Applications are especially inclined to use MySQL databases that are widely used, but there are also bindings with many other RDBMS, such as IBM? DB2 ?.

If you want to, you can add Ruby code to perform additional verification in the application model, enhance data association, or trigger other operations. The Ruby file in the app/models/directory of the application can call multiple verification methods of ActiveRecord. However, you can also leave the model code as a stub, instead of relying on the RDBMS constraints for data storage. For example, the application I developed in this example only contains the skeleton model code (at least at the beginning ):
Listing 1. skeleton model app/models/contact. rb

class Contact < ActiveRecord::Baseend


The Controller executes the logic of the application in its abstract form. That is to say, the Ruby script in the app/controllers/directory of the application can import the model data as a variable, save it back, or modify and process it. However, the controller does not care how users properly display or input data. In the common MVC model, this allows users to interact with the same controller in multiple ways: Local GUI, Web interface, and the voice interfaces used by people with poor eyesight can interact with the same controller.

However, Rails is not as common as that; instead, it is limited to providing and collecting data on Web pages. Even so, you can modify the layout of those Web pages-color, Font, table, style form, and so on-not related to the Controller code.

The Rails view is where we write Ruby code. Rails contains a very good template language for. rhtml, which combines pure HTML with embedded Ruby code. The most superficial appearance of the Rails application interface is usually controlled by the CSS style form .. Rhtml is an enhanced HTML format. In fact, a simple HTML file is also a legal RHTML template. However, you should not ignore the script control that RHTML provides for you.

RHTML is the real template format-not only the method of embedding code in HTML-this is a more effective method. If you are familiar with PHP, you can consider the comparison between PHP and Smarty templates. That is to say, the embedded script only blends the Code with uninterpreted HTML. When some content needs to be output to the client, the Code part is still responsible for executing the print statement.

The template engine adds a set of custom tags to HTML, allowing you to express conditions, loops, and other logic as part of the enhanced HTML Tag.

Generate code

The tool provided by Rails is mainly a set of code generators. This method is preferred for development environments that force me to use a strict workspace and IDE. Rails will not impede you, but it will save you most of the work of manual programming-or by providing the "freely available" first-pass bracket (scaffolding ), at least it helps you easily divide the work that requires manual encoding into multiple parts.

The concept of bracket is the core concept in Rails. Very simple applications may not require coding at all, so Rails can dynamically generate client HTML pages at runtime. The first step is to generate a rough bracket. Next, you can generate more detailed controllers, views, and models that can be customized. However, you do not need to generate too many instances at the beginning.

Rails has a fixed and common structure for its files, but such organization is relatively strict. If you try to forcibly organize other files and code, you may have to make efforts to modify the Rails environment. Furthermore, I cannot find any reason not to use the organization method provided by Rails; in most cases, it is "fits your brain" (which Ruby supporters like to talk about ). For example, if you design a framework from the ground up (at least if you think "Ruby"), these directory names and their organizations may be very close to your choice.

Build a simple application

There are some tutorials on the Ruby on Rails Web site to guide you through creating a simple Rails application (see references ). The example program here is similar to this, because the correct method for building a Rails application is correct. Because the length of this introduction is relatively short, I strongly recommend one of those long tutorials so that you can lay a more comprehensive foundation.

The example application is a basic address book. It demonstrates the general steps for creating an application:

Generate a model (create a MySQL database and table in this step ).
Generate applications (including generating basic code and directories ).
Start Rails (and configure database access ).
Create some content (including generating the bracket model and controller, and telling the Controller to use that bracket ).

We will look at each step in detail.
Generate AddressBook Model

The first thing you need to do for any application is to create a database for storing data for it. Technically, this step does not need to be performed first, but must be completed in an early stage. You should create a database before writing any application code (or even automatically generated code). This should be obvious. Therefore, let's create a database in the MySQL database and create the first table in the database. (Read other documents to learn how to install and run MySQL or other RDBMS .)

We assume that MySQL has been installed and is available.
List 2. Create a MySQL database and table

[~/Sites]$ cat AddressBook.sqlCREATE DATABASE IF NOT EXISTS AddressBook;USE AddressBook;CREATE TABLE IF NOT EXISTS contacts ( id smallint(5) unsigned NOT NULL auto_increment, name varchar(30) NOT NULL default '', created_on timestamp(14) NOT NULL, updated_on timestamp(14) NOT NULL, PRIMARY KEY (id), UNIQUE KEY name_key (name)) TYPE=MyISAM COMMENT='List of Contacts';[~/Sites]$ cat AddressBook.sql | mysql

Note some points in the first table. The most important thing is that each table must have an id column, and the column name is id. Rails uses the primary key column id to complete various record persistence and reference tasks. The created_on and updated_on domains are not required. However, if you use them, Rails automatically maintains them in the background; in most cases, using these timestamps is nothing bad. Therefore, the "real" data you want to add is only the name of the address book content.

Another odd aspect is that Rails uses singular and plural names for different content. According to the context, entries are renamed as singular or plural. The table name must be in the plural format. I have no experience using irregular plural words; words such as datum and data may cause problems in Rails.
Generate the AddressBook Application

Now that you have an interactive database, you can create the AddressBook application. The first step is to simply run rails to generate the basic directory and support code:
Listing 3. Generating basic code and directories

[~/Sites]$ rails AddressBookcreatecreate app/apiscreate app/controllerscreate app/helperscreate app/modelscreate app/views/layoutscreate config/environmentscreate components[...]create public/imagescreate public/javascriptscreate public/stylesheetscreate script[...]create READMEcreate script/generatecreate script/server[...]

I deleted the output for running rails. The ignored rows only remind you of the various files and directories you have created. Run it on your system to browse all generated files. I have displayed some of the most important files and directories in the code.
Run Rails

After creating the AddressBook/directory and required sub-directories, you need to perform a unique initial configuration. First, modify the YAML configuration file to set the database as follows:
List 4. Configure Database Access

[~/Sites]$ cd AddressBook[~/Sites/AddressBook]$ head -6 config/database.yml # after editingdevelopment: adapter: mysql database: AddressBook host: localhost username: some_user password: password_if_needed

Finally, you need to provide data. Rails comes with its own single-function Web server, WEBrick, which is very suitable for our experiments. You may also follow the instructions on the Ruby on Rails Web site to configure Apache or other servers to use FCGI (or common CGI, but common CGI will be slow) provides services to Rails Applications.
Listing 5. Start the WEBrick Server

[~/Sites/AddressBook]$ ruby script/server -d=> Rails application started on[2005-03-21 17:57:38] INFO WEBrick 1.3.1[2005-03-21 17:57:38] INFO ruby 1.8.2 (2004-12-25) [powerpc-darwin7.8.0]

Create some content

The previous steps are sufficient to see a welcome page on the WEBrick port. For example, in my local system, you can now access the http://gnosis-powerbook.local: 3000 /. However, a little more code needs to be generated to operate custom databases. You can use the generate script to complete this task. This script is created in the AddressBook/application directory:
Listing 6. Stent model and controller code generation

[~/Sites/AddressBook]$ ruby script/generate model contact   exists app/models/   exists test/unit/   exists test/fixtures/   create app/models/contact.rb   create test/unit/contact_test.rb   create test/fixtures/contacts.yml[~/Sites/AddressBook]$ ruby script/generate controller contact   exists app/controllers/   exists app/helpers/   create app/views/contact   exists test/functional/   create app/controllers/contact_controller.rb   create test/functional/contact_controller_test.rb   create app/helpers/contact_helper.rb

Note: In the corresponding table name, the contact number of the singular number should be used, instead of the contacts of the plural number.

Now you need to edit one or more generated files (only a few edits are required) to allow the Controller to use the bracket:
Listing 7. Inform the Controller to use the bracket

[~ /Sites/AddressBook] $ cat app/controllers/contact_controller.rb
Class ContactController <ApplicationController
Model: contact
Scaffold: contact

You can now view and modify the contents of the database through a URL similar to the http://rails.server/contact/ (http://gnosis-powerbook.local: 3000/contact/in my test case. After entering some data, it looks like 1 and 2:
Figure 1. List contacts

Figure 2. edit a contact

Create customizable content

The previous Code creates a complete interface for viewing and modifying database functions. However, all formatting, display, and business logic (such as the original one) are dynamically completed by Rails, no major changes. To create more customized content, you need to generate more code. What we need now is to allow Rails to explicitly write all the brackets it implicitly generates at runtime so that we can modify them.
Figure 8. Explicit controller and view code generation

[~/Sites/AddressBook]$ ruby script/generate scaffold Contact dependency model   [...]   create app/views/contacts   exists test/functional/   create app/controllers/contacts_controller.rb   create test/functional/contacts_controller_test.rb   create app/helpers/contacts_helper.rb   create app/views/layouts/contacts.rhtml   create public/stylesheets/scaffold.css   create app/views/contacts/list.rhtml   create app/views/contacts/show.rhtml   create app/views/contacts/new.rhtml   create app/views/contacts/edit.rhtml

Now you have more to do, so try to modify some content. (Note that this code has used contacts in the plural format again. I don't know why; now we need to accept it .) Try to modify some colors and fonts in CSS:
Listing 9. configure a cascading style form

[~/Sites/AddressBook]$ head -8 public/stylesheets/scaffold.cssbody { background-color: #ffe; color: #338; }body, p, ol, ul, td { font-family: verdana, arial, helvetica, sans-serif; font-size:  13px;}td { border: 1px solid; }a { color: #eef; background-color: #446; }a:hover { color: #fff; background-color:#000; }

You already have this code, so what does contacts_controller.rb do? It is more explicit and configurable than contact_controller.rb in the previous code. The Controller is similar to the following:
Listing 10. Controller app/controllers/contacts_controller.rb

class ContactsController < ApplicationController def list  @contacts = Contact.find_all end def show  @contact = Contact.find(@params['id']) end def create  @contact =['contact'])  if   flash['notice'] = 'Contact was successfully created.'   redirect_to :action => 'list'  else   render_action 'new'  end end

As mentioned above, the main task of the controller is to import data into variables. The object Contact is the ActiveRecord object-link ing provided by the model. The variable @ contacts or @ contact is the data given in their appropriate methods. Through a URL you can access those methods themselves, such as the http://rails.server/contacts/show/2 (this method shows contacts with id "2 ).

In this example, the controllers eventually connect to the view, that is, the RHTML file, which uses the data values that the controllers import to the variables. For example, here is part of the list View:
Listing 11. list View apps/views/contacts/list. rhtml

[...]<% for contact in @contacts %> <tr> <% for column in Contact.content_columns %>  <td><%=h contact.send( %></td> <% end %>  <td><%= link_to 'Show', :action => 'show', :id => %></td>  <td><%= link_to 'Edit', :action => 'edit', :id => %></td>  <td><%= link_to 'Destroy', :action => 'destroy', :id => %></td> </tr><% end %>[...]

Method ContactsController. list: import the variable @ contacts. The flow control label in RHTML extracts a single record from the array.

Modify Model

The initial model only contains the contact name. Unfortunately, I have no room to extend this model to include actual contact data, such as phone numbers, addresses, and emails. Generally, the data should be stored in a sub-table, and the external Keywords of the sub-table are associated with the table contacts. The Rails model uses custom code like this to specify the association:
Listing 12. Custom Code app \ models \ phone. rb

class Phone < ActiveRecord::Base belongs_to :contactend

Before the end, let's make a slight modification to the data model to see how it affects the application. First, add a column:
Listing 13. Add first_met data to the model

$ cat add-contact-date.sqlUSE AddressBook;ALTER TABLE contacts ADD first_met date;$ cat add-contact-date.sql | mysql

Since the underlying model has been modified, the http://rails.server/contact/-the back-end version of the bracket-will be adjusted directly, no need for you to do anything. The Controller and view are completely model-based. However, the application version on the http://rails.server/contacts/ uses the files we manually write, not that automated.

In the list view, Contact. content_columns is used as part of the template loop and all columns can be queried automatically, no matter what they are. However, other views such as edit have been generated and a new data field needs to be added. For example:
Listing 14. edit view app/views/contacts/edit. rhtml

What does the application you manually modify look like? It is not very different from the default one. However, you can see in figure 3 and 4 that the modification has taken effect:
Figure 3. List contacts. After modification

Figure 4. Edit the contact after modification


Rails provides you with an extremely fast way to develop flexible Web applications. This article only covers how to use Rails. The complete framework contains many practical classes and methods that can be used most by Web-based applications.

The biggest value of Rails is that it breeds a systematic "Rails Way of Thinking", because all the support code you need makes it complete. This is a huge advantage over other toolkits and frameworks that only provide raw materials to use. Rails development provides you with a smooth way to implement the idea of half-formed as a fully functional Web application.

Related Article

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: 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.