Parsing of MVC structure data transmission in Ruby on Rails, railsmvc

Source: Internet
Author: User

Parsing of MVC structure data transmission in Ruby on Rails, railsmvc

If you have already developed a Rails-based application but are still confused about the data transmission between MVC, congratulations! This article is just to summarize the methods and techniques of Rails data transmission. Ruby on Rails 3 (hereinafter referred to as Rails 3) is the current major release version. The content and code described in this article are based on this version.
Introduction to Rails 3

Ruby on Rails is an open-source Web application development framework that is implemented in Ruby and adopts the MVC mode. It provides a full set of solutions for Web applications. Its design philosophy of "Conventions are better than configurations" allows Web developers to free themselves from tedious configurations and focus on the core application logic. Rails provides functions and specifications that can be used directly based on the best experience and habits, rather than requiring developers to perform complex configuration files. Ruby on Rails's fast and high-quality development features and a large number of free plug-ins attract a large number of new Internet giants, including Twitter, Groupon, And Hulu.

Quickly create a Rails 3 Application

To gradually demonstrate the features of Rails 3, a simple blog model is developed in incremental mode. After Rails3 is installed, run the command Rails new demoBlog.

All types of files required by the demoBlog application are automatically generated. Enter the generated folder demoblog and run the gem command required to automatically install demoBlog: bundle install.

Then, configure the database file in $ rorails/demoblog/config/database. yml and run the command to create a database: rake db: create.

Now, the simple demoBlog is created and the server startup command is rails server.

Open http: // localhost: 3000 to view the typical welcome page of Rails 3, as shown in figure 1.
Figure 1. Typical welcome page of Rails 3

Rails scaffolding allows you to quickly create models, views, and controllers for new resources without having to deal with the details. Run the following command to create an article scaffold for demoBlog to manage the articles in the blog. Run the scaffolding creation command: rails generate scaffold Article title: string keywords: string content: text

This generates the View File of the article controller, article, and the article model containing the title, keyword, and content attributes. Run the database migration command to generate the related data table: rake db: migrate. In this case, a simple but structured document management system is developed. You can directly access the article Management page through URL: http: // localhost: 3000/articles.

Rails 3 MVC Architecture

Rails 3 uses the MVC (Model, View, Controller) Hierarchical architecture to implement core functional modules. This not only makes the business logic independent from the user interface, but also makes the code clear and easy to maintain. It also improves the code reuse rate and achieves the Rails principle of "not repeating yourself. The MVC functions in Rails are as follows:

  • Model: Data Information of the application system and rules for operating the data;
  • View: it represents the user interface of the application system. It is usually an HTML file containing embedded Ruby Code and is used to provide data to the browser;
  • Controller: mainly responsible for processing Web requests, retrieving model data, and passing the data to the view as required. A controller is a bridge between a model and a view.

The demoBlog application created in the preceding document is used as an example. To access the article list, enter the URL of the page: http: // localhost: 3000/article to open the page, the corresponding Web request processing process 2 is shown in the following steps:

  • The browser sends a Web Request
  • The routing module sends the request information to the corresponding controller, and the Controller determines how to process the request;
  • The Controller calls the corresponding model to complete the business logic based on the request processing logic;
  • Complete data retrieval or storage based on actual needs;
  • The Controller organizes processing information and calls the view to parse the data returned from the model;
  • Complete page rendering and return the data to the browser.

Figure 2. Rails 3 MVC event processing Flowchart

Through the typical internal processing process of Rails 3, we can see that the MVC structure of Rails 3 is clear and the division of labor is clear. How do these closely related modules complete data transmission? Many beginners are confused about this. I will analyze it in detail below.

Data transfer methods between controllers and views

Open the view folder and find the source file $ rorails/demoBlog/app/views/articles/index.html. erb used to implement the article list. The code shown in Listing 1 is displayed. This code iterates on the variable @ articles to display the attribute values of the list of all articles.
Listing 1. View index.html. erb code snippet

 <% @articles.each do |article| %>  <tr>   <td><%= article.title %></td>   <td><%= article.keywords %></td>   <td><%= article.content %></td>   <td><%= link_to 'Show', article %></td>   <td><%= link_to 'Edit', edit_article_path(article) %></td>   <td><%= link_to 'Destroy', article, :confirm =>   'Are you sure?', :method => :delete %></td>  </tr>  <% end %>

What puzzles beginners is: where does the variable @ articles come from? To solve this problem, open the source file $ rorails/demoblog/app/controllers/articles_controller.rb of the article controller and find the file with index.html. the index method corresponding to erb. You can see the variable @ articles, as shown in Listing 2. The @ articles variable in the view is generated by the Controller and assigned to the view. The transfer process is transparent to developers. In other words, a view can directly use the variables of the corresponding method in the corresponding controller.
Listing 2. code snippet for retrieving data in the Controller

 def index   @articles = Article.all   respond_to do |format|    format.html # index.html.erb    format.xml { render :xml => @articles }   end  end

The user opens http: // localhost: 3000/articles/new to post a new article. The controller will use @ Article = article. new: Creates NULL data based on the Article model and transmits it to new.html. erb view, as shown in figure 3. Enter data on this blank page and click "Create Article" to Create an Article. After the document is created successfully, the system returns the prompt message indicating that the document is successfully created and the content of the newly created article, as shown in figure 4. This seems like a simple process. It actually involves the process of transferring data from a form to a controller and then to a model to complete storage.
Figure 3. Create an article

Figure 4. Article created successfully

The code for rendering the view is located in _form.html. erb (called by new.html. erb ). After you click Submit, Rails will jump to the create method of the controller according to the routing rules. The process is simple, but how does the data filled in the form be transmitted to the controller?

The create method of the controller is shown in listing 3. To create a new article object, the create method reads data from params: The article parameter. Here, params is a hash table, which is one of the most important Transfer Parameters in Rails and contains the data transmitted by browser requests. It is this params that transmits data from the client form to the Controller. For example, the newly created article form data (including Title, Keywords, Content) will be encapsulated into the article object and transmitted to the Controller through params.
Listing 3. create method of the Controller

 def create   @article = Article.new(params[:article])   respond_to do |format|    if @article.save     format.html {    redirect_to(@article, :notice => 'Article was successfully created.') }    format.xml {    render :xml => @article, :status => :created, :location => @article }    else     format.html {    render :action => "new" }     format.xml {    render :xml => @article.errors, :status => :unprocessable_entity }    end   end  end

The Rails application can transmit data to params in two ways, which is then obtained by a certain method of the controller. One is to encapsulate the data entered into the HTML form into an HTTP request and pass the data to the Controller's params through the POST method. This method is used to submit the form data of new.html. erb through the POST method. Another way is to place the data in the URL as part of the URL? It is usually called a URL query string parameter. Rails does not differentiate the data transmitted by the two methods. controllers can obtain data from params using the methods described earlier. Take URL: http: // 127.0.0.1: 3000/articles? Keywords % 5b % 5d = Hello & keywords % 5b % 5d = Test & keywords % 5b % 5d = Article. For example, params [: keywords] will store ["Hello ", "Test", "Article"].

Data transmission methods and techniques between controllers and Models

As shown in figure 2, the controller is a key component connecting the view and model. It not only receives form data from the view, but also transmits data in the model to the view. Compared with data transmission between controllers and views, data transmission between controllers and models is easier to understand.

Refer to code listing 3. The controller creates an Article instance using the article. new (params [: Article]) method, and then stores the data in the database table by @ article. save. This process is so simple that it seems that the controller is directly exchanged with the database and does not involve any model. Open the model source file $ rorails/demoblog/app/models/article. rb, as shown in Listing 4. The model code is so concise that it does not even have common attribute definitions in the object-link model. In fact, model attributes in Rails are associated with database fields based on naming rules. The attribute definition of model data is in the corresponding migrate file. The Controller directly uses the create, save, update, and other methods inherited from the parent class ActiveRecord: Base to create, store, and update data without writing additional code.
Listing 4. Code of the Article Model

 class Article < ActiveRecord::Base  end

In Rails, the process of obtaining model data by a controller is quite convenient and convenient. Open the Controller source file, as shown in listing 5. Rails transmits the ID value in the request URL to the Controller through params according to routing rules. The Article. find method searches for existing data based on: id, and then uses the update_attributes method to update the record. The Rails controller reads data from the model through the find method of ActiveRecord.
Listing 5. Controller update Method

 def update   @article = Article.find(params[:id])   respond_to do |format|    if @article.update_attributes(params[:article])     format.html {     redirect_to(    @article, :notice => 'Article was successfully updated.') }     format.xml { head :ok }    else     format.html { render :action => "edit" }     format.xml {     render :xml =>     @article.errors, :status => :unprocessable_entity }    end   end  end

Rails 3 encapsulates the data ing relationships between controllers, models, and databases, which greatly simplifies the data operation process and facilitates data access exceptions, this fully demonstrates Rails's design philosophy of "Conventions are better than configurations.

Share data in a view
Data sharing between views and la s

After Rails 3, the view layout generated by scaffolding is located in layouts/application.html. erb and can be shared by all controllers. The layout and view can share data in the controller. That is to say, the layout can obtain data in the Controller in the same way as the view.

However, in some special cases, the layout needs to read some view information. Taking demoBlog as an example, to display the total number of articles on the title page of the article list, you can add code at the end of index.html. erb, as shown in Listing 6.
Listing 6. View index total number of articles read

 <% content_for :ArticleNumber do %>  <%= @articles.length %>  <% end %>

Add the yield Method to the header of the layout source file, as shown in listing 7. In this way, the information in the <% content_for: ArticleNumber do %> label can be displayed at the specified position <% = yield: ArticleNumber %>. The final display effect of the number of articles in the page header is 5.
Listing 7. Display by layout source files

 

Figure 5. Final display of the total number of articles

The above example is special, but it illustrates the layout method for reading View data. Note that the layout cannot transmit information to the view, because the view is executed before the layout is introduced or takes effect.
Data between views

Data is often transferred between views. Rails has been carefully designed for this purpose. It not only provides unique flash shortcuts, but also supports traditional Session and Cookie functions. It should be noted that the data transfer process described in this section is essentially from the Controller to the view. Because for users, data is obtained from a view and then displayed in another view. Because the intermediate controller is almost transparent to developers, you should define this type as data transmission between views.

Rails's flash Mechanism is especially suitable for transferring data between pre-and post-associated view pages. In essence, flash is a built-in hash table in Rails that is used to send user-required messages from one controller to the view of another controller. When the Controller calls redirect_to, the redirection clears all variables except flash.

Taking the article modification and update as an example, you need to tell the user the result on the next page (the page of the article is displayed here, corresponding to the show action. The update method is shown in listing 5. Obviously, the message 'Article was successfully updated is displayed when the update is successful. 'assigned to: notice, which is the most commonly used key of the flash hash table. Besides: notice, the: error,: alert, and warning keys are also quite common. The message indicating that the article is successfully updated is displayed in effect 6.
Figure 6. Prompt that the article is updated successfully

Generally, data added to flash can be read in the next request. However, in some cases, you want to use it directly in the current request. For example, if an article fails to be created and the page is rendered directly, no new request will be generated. If you need to display the information in flash, you can use the flash. now method.

Note the following when using flash: first, to ensure performance, the data stored in flash cannot be too long. Second, flash content can only be redirected once. If you want data to remain valid after redirection, you need to use flash. keep before redirection.

To demonstrate how Rails uses cookies and sessions, the reader comment function is added here. The entire creation process is very simple. With the next command, you can create the database tables required for comments and implement nested ing:

rails generate model Comment user:string comment:text article:references

Run the database migration command rake db: migrate and add the comment display code to get the reader comment function shown in 7.
Figure 7. Comments by readers

Cookies are usually sent by the server to the browser and are used to store text of a small amount of user information. In most cases, applications based on Rails do not need to directly access cookies because the built-in session mechanism or third-party plug-ins of Rails support user information management. Data stored in cookies can be accessed across requests or sessions. Therefore, users can directly use cookies to access data.

Rails provides simple Cookie access methods. To remind users to use the same user name to post comments, cookies are used to save the user name used for the last comment. As shown in listing 8, the user name is read or saved through cookies [: name.
Listing 8. Create a comment controller code snippet

 class CommentsController < ApplicationController  def create   @last_name = cookies[:name]   @name = params[:comment][:user]   unless @name == @last_name    cookies[:last_name] = @last_name    cookies[:name] = @name   else    cookies[:last_name] = nil   end  end  end

In article controller, as shown in listing 9, you can read the data stored in Cookies for ease of use. The comment page shows the result 8.
Listing 9. Using cookies to operate data

 def show   @article = Article.find(params[:id])   @last_name = cookies[:last_name]   unless @last_name == nil   @name = cookies[:name]  end

Figure 8. Comment display

Rails Applications often use sessions to transmit data between multiple requests. session objects can be used in controllers and views. Now we add a new session object to save the list of names used by users. In CommentsController, the operation of the session object is shown in listing 10.
Listing 10. code snippet for data operation through session

  @names = session[:name]   if @names    @names = []   end   if @name    @names << @name   end   session[:names] = @names

Add the code to display the user name list in the view, as shown in listing 11. The final result of the page is 9.
Listing 11. Code for reading the user name list from the View

 <% if @names %>  <p>The names you have used:</p>  <ul>  <% @names.each do |name| %>   <li><%=h name %></li>  <% end %>  </ul>  <% end %>

Figure 9. User List displayed on the page

In terms of the implementation effect, flash, cookie, and session can complete data transmission between views. However, flash is generally used for simple message prompts, while cookies and sessions are common in user information management.

Conclusion

Based on the actual demo program, this article first introduces the MVC Architecture of Rails 3, and then gradually introduces the relationship between the Controller and the view, the controller and the model, and the view, the data transmission methods and techniques are analyzed in detail.

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