Anatomy of data passing in Rails 3 MVC

Source: Internet
Author: User
Tags ruby on rails

This paper analyzes the MVC architecture of Rails 3 and discusses the methods and techniques of data transfer between the controller and view of Rails 3, controller and model, view and layout, and multiple views. Assuming you have a basic understanding of Ruby on Rails, you can at least configure Ruby on rails and run a getting Started application like Hello world.

0 Reviews:

Lin Hongxiang, software engineer, IBM

August 29, 2011

    • Content

Develop and deploy your next application on the IBM Bluemix cloud platform.

Start your free trial now

If the reader has already developed rails-based applications, but there is a lot of confusion about the data transfer between its MVC, congratulations, this article is to summarize the methods and techniques of data transfer in rails. Ruby on Rails 3 (hereinafter referred to as Rails 3) is the current major release, and the content and code described in this article are based on this version.

About Rails 3

Ruby on Rails is a ruby-implemented, open-source web application Development framework that uses MVC patterns to provide a complete solution for Web applications. Its "Custom convention is better than configuration" design philosophy, so that Web developers can be freed from cumbersome configuration, focus on the core application logic. "Custom conventions better than configuration" is Rails that provide direct-use functionality and specifications based on best practices, rather than requiring developers to make specific cumbersome settings through complex configuration files. Ruby on Rails's fast, high-quality development features and its plethora of free plugins have attracted a large number of Internet upstarts, including Twitter, Groupon and Hulu.

Back to top of page

Quickly create a Rails 3 application

To step through the features of Rails 3, a simple blog model is developed here in incremental mode. After installing RAILS3, run the command: Rails new Demoblog.

The various files required by the Demoblog application are automatically generated. Go to the generated folder Demoblog, run the command that automatically installs the gem required for Demoblog: bundle install.

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

Now that the simple Demoblog is created, run the server startup command: Rails server.

Open http://localhost:3000 to see the typical Welcome page for Rails 3, as shown in 1.

Figure 1. Typical Welcome page for Rails 3

Rails Scaffolding can quickly build models, views, and controllers for new resources without having to deal with the details. Run the following command directly to create a article scaffold for Demoblog to manage the articles in your blog. Run Scaffolding Build command: Rails Generate scaffold article title:string keywords:string content:text

This generates a article controller, a article view file, and a article model with three attributes of title, keyword, and content. Run the Database Migration command to generate the relevant data table: Rake db:migrate. At this point, a simple but structured article management system is developed. Direct access to its Article Management page is available through url:http://localhost:3000/articles/.

Back to top of page

Rails 3 MVC Architecture parsing

Rails 3 implements the core function module in the MVC (model model, view view, Controller) hierarchical architecture. This not only makes the business logic independent of the user interface, the code is clear and easy to maintain, but it also increases the reuse of code, achieving the "Don't repeat yourself" principle of Rails. The features of MVC in Rails are as follows:

    • Model: The data information representing the application system and the rules for manipulating the data;
    • View: The user interface that represents the application system, usually an HTML file that contains embedded Ruby code to provide data to the browser;
    • Controller: primarily responsible for processing WEB requests, retrieving model data and passing data to the view as required. A controller is a bridge between a model and a view.

As an example of the Demoblog application created above, for the user to access the list of articles, enter the page's Url:http://localhost:3000/article open page, corresponding to the WEB request processing Flow 2, the approximate steps are as follows:

    1. Browser makes WEB requests
    2. The routing module sends the request information to the appropriate controller, which is determined by the controller to handle the request;
    3. The controller invokes the corresponding model to complete the business logic according to the request processing logic;
    4. According to the actual needs, the completion of data retrieval or storage;
    5. The controller organizes the information and invokes the view to parse the data returned from the model;
    6. Complete the page rendering and return the data to the browser.
Figure 2. Rails 3 MVC Event processing flowchart

With the typical internal processing flow of rails 3, you can see that the MVC structure of rails 3 is clearly structured and clearly divided. So what are some of the techniques that are closely linked to the data transfer? Many beginners are puzzled by this, the author will be in the following detailed analysis and introduction.

Back to top of page

The technique of data transfer between controller and view

Open the View folder and find the source file that implements the list of articles $rorails/demoblog/app/views/articles/index.html.erb, and you can see the code shown in Listing 1. This code iterates over the variable @articles, showing the property values for all the list of articles.

Listing 1. View Index.html.erb Code Snippets
<% @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 =     ' is you sure? ',: Method =:d elete%></td>   </tr >  <% End%>

To the beginner's confusion, where does the variable @articles come from? To solve this problem, open the source file of the article controller $rorails/DEMOBLOG/APP/CONTROLLERS/ARTICLES_CONTROLLER.RB, and find the index method corresponding to Index.html.erb. You can see the variable @articles, as shown in Listing 2. The @articles variables in the view are generated by the controller and then passed to the view, and the delivery process is transparent to the developer. In other words, the view can directly use variables corresponding to the corresponding method in the controller.

Listing 2. Code snippet to get 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 publish a new article, and the controller creates a data that is empty based on the article model by @article = Article.new, and then transmits it to New.html.erb View, shown in effect 3. The user fills out the data on this empty page and clicks on "Create article" and creates the article. The article was created successfully, returning the article to create a successful message and the content of the newly created article, as shown in 4. This seems like a simple process that actually includes the process of passing data from a form to a controller and passing it to the model to complete the storage.

Figure 3. Create a new article in Figure 4. Article Creation success

The code for the rendered view is in _form.html.erb (called by New.html.erb). After the user clicks Submit, Rails jumps to the controller's create method according to the routing rules. The process is simple, but how is the data that the user fills out into the form passed to the controller?

The controller's Create method is shown in Listing 3 below. In order to create a new article object, the Create method reads the data from the params: article parameter. The params here is a hash table, which is one of the most important pass parameters in Rails, containing the data that the browser requested to pass. It is this params that passes data from the client form to the controller. For example, the new article form data (including title,keywords,content) will be encapsulated in the article object and passed to the controller via the params.

Listing 3. The 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 =: U Nprocessable_entity}       end End end   

The Rails application can pass data to the params in two ways, which is then obtained by a method of the controller. One is to encapsulate the data that the user enters into an HTML form into an HTTP request and pass the data to the controller's params via the POST method. This is how the form data for the New.html.erb view is submitted through the POST method. Another way to do this is by using the data as part of the URL, in the URL? After that, it is commonly referred to as a URL query string parameter. Rails does not differentiate between the data passed by the two methods, and the controller can get the data from the params in a way previously described. Taking url:http://127.0.0.1:3000/articles?keywords%5b%5d=hello&keywords%5b%5d=test& Keywords%5b%5d=Article as an example, Params[:keywords] will store ["Hello", "Test", "article"].

Back to top of page

The technique of data transfer between controller and model

As shown in 2, the controller is a key component of the connection view and model, which not only receives form data from the view, but also passes the data in the model to the view. The data transfer between the controller and the model is easier to understand than the data passing between the controller and the view.

Referring to listing 3, the controller creates an article instance through Article.new (Params[:article]) and then stores the data in a database table by the @article. Save. The process is so simple that it looks like the controller is switched directly to the database and does not involve any model. Open the model source file $rorails/rorails/demoblog/app/models/article.rb, as shown in Listing 4. The model code is so concise that even the attribute definitions that are common in the entity Relationship model are not. In fact, the properties of a model in Rails are associated with a database field implementation by naming the rules. The property definition of the model data is in the corresponding migrate file. The controller uses methods such as Create,save and update, which inherit from the parent class activerecord::base, to create, store, and update data without the need for additional coding.

Listing 4. Code for the article model
Class article < ActiveRecord::Base  end

In Rails, the controller obtains the model data process is also quite convenient and quick. Open the Controller source file and the Update method is shown in Listing 5. Rails passes the ID value in the request URL to the controller through the params according to the routing rules. The Article.find method finds existing data based on: ID and then updates the record using the Update_attributes method. The Rails controller reads data from the model through the ActiveRecord Find method.

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   

Rails 3 encapsulates the data mapping relationship between controllers, models, and even databases, greatly simplifying the process of data manipulation, the data access is exceptionally convenient, and fully embodies the "custom convention better than configuration" design philosophy of rails.

Back to top of page

Data sharing in views and data sharing between layouts

After Rails 3, a scaffolding-generated view layout is located in Layouts/application.html.erb, which can be shared by all controllers. Layouts and views can share data in a controller. That is, the layout can get the data in the controller in exactly the same way as the view.

However, in some special cases, the layout needs to read some view information. In Demoblog, for example, to be able to display the total number of articles on the title of the page in the article list, you can add the code at the end of Index.html.erb as shown in Listing 6.

Listing 6. View index reads the total number of articles
<% content_for:articlenumber do%>   <%= @articles. Length%>  <% End%>

In the header of the layout source file, add the yield method, as shown in Listing 7. This allows the information in the <% content_for:articlenumber do%> tag to be displayed in the location specified in the <%= yield:articlenumber%>. The article number information is shown in the final display of the page header 5.

Listing 7. Display by layout source file
Figure 5. The final display effect of the total article number

The above example is quite special, but it is a good way to illustrate the layout of reading view data. It is important to note that layouts are not able to pass information to the view because the execution of the view is before the introduction of the layout or the effect.

Data between views

There is often a need to pass data between views, and Rails is well-designed for this. It not only provides a unique flash shortcut mechanism, but also supports the traditional Session and Cookie functions. It should be noted that this section describes the data passing process, essentially from the controller to the view. Because for the user, the data is fetched from one view and then displayed through a different view. Because the middle controller is almost transparent to the developer, this type is defined as data passing between views.

Rails ' flash mechanism is especially useful for passing data between front and back associated view pages. Essentially, Flash is a built-in, Rails hash table for sending messages from one controller to another view of the controller. When the controller calls Redirect_to, the redirect empties all variables except Flash.

As an example of the article modification update, you need to tell the user the results of the next page (here is the page that displays the article, corresponding to show action). The corresponding Update method is shown in Listing 5 of the preceding code, and it is clear that the update succeeded prompt message ' article was successfully updated. ' Assignment to: notice, which is the most common key for flash hash tables. In addition to: notice,: Error,: Alert, warning key is also quite common. The message that prompted the article to update successfully appears as shown in effect 6.

Figure 6. Prompt article update success

Typically, the data added to Flash can be read in the next request immediately thereafter. However, in some cases, you want to use it directly in the current request. For example, if the creation of the article fails and the page is rendered directly, it will not cause a new request. If you need to display information in Flash at this point, you can use the Flash.now method.

The use of flash must pay attention to several points: first, in order to ensure performance, flash storage data can not be too long. Second, Flash content can only be redirected once, and if you want the data to remain valid after redirection, you need to use flash.keep before redirection.

To demonstrate how Rails uses cookies and sessions, this article adds reader comment functionality. The entire creation process is simple, and one of the following commands enables you to create the database tables required for comments and to implement nested mappings:

Rails Generate model Comment user:string comment:text article:references

Run the Migrate database command: Rake db:migrate, add a comment display code, you can get 7 of the reader comment function.

Figure 7. Readers post comments

Cookies are usually text that is sent to the browser by the server to store a small amount of user information. Rails-based applications do not require direct access to cookies in most cases, because the built-in session mechanism of rails or third-party plug-ins can support user information management. The data stored in the cookie can be accessed across requests or even across sessions, so users can access the data directly using cookies.

Rails provides a very simple way to access cookies. To prompt users to comment using the same user name, a Cookie is used here to save the user name that the user used when they last posted a comment. Read or save the user name, as shown in Listing 8, via Cookies[:name].

Listing 8. Create a comment for the 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 the article controller, as shown in Listing 9, the data stored in the cookie can be read out and used very conveniently. The comment page appears as shown in 8.

Listing 9. Manipulating data with cookies
def show     @article = Article.find (Params[:id])     @last_name = Cookies[:last_name]     unless @last_name = = Nil     @name = cookies[:name]  End
Figure 8. Article Comments Show effect

Rails applications often use sessions to implement data transfer between multiple requests, and session objects can be used in both the controller and the view. Now we have added a new session object to hold the list of names used by the user. In Commentscontroller, the session object operates as shown in Listing 10.

Listing 10. Code snippet for manipulating data via session
    @names = Session[:name]     if @names       @names = []     end     if @name       @names << @name     End     Session[:names] = @names

In the view, add the code that displays the list of user names, as shown in Listing 11. The page finally shows the effect as shown in 9.

Listing 11. Code for the view to read the list of user names
<% if @names%>  <p>the names you have used:</p>  <ul>   <% @names. Per do |name|% >     <li><%=h name%></li>   <% end%>  </ul>  <% End%>
Figure 9. Show user list on page

From the implementation of the effect, Flash, cookie and session can complete the data transfer between views. However, Flash is generally used for simple informational messages, while cookies and sessions are common in user information management.

Back to top of page

Conclusion

This paper introduces the MVC architecture of Rails 3, and then introduces the relationship between controller and view, controller and model and view, and analyzes the technique of data transfer in detail.

Anatomy of data passing in Rails 3 MVC

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.