CSC/ECE 517 Fall 2011/ch4 4d ls

From Expertiza_Wiki
Jump to navigation Jump to search

CSC/ECE 517 Fall 2011/ch4 4d ls


Introduction

What is ruby on rails<ref>http://en.wikipedia.org/wiki/Ruby_on_Rails</ref>? What does framework <ref>http://en.wikipedia.org/wiki/Framework</ref>mean and what can it achieve? What is MVC<ref>http://www.tutorialspoint.com/ruby-on-rails/rails-framework.htm</ref> and what is its advantage? This article will not only eliminate the above questions in your heart, but also will provide you a practical experience of building a cookbook application and discuss the individual part of the functionality and the operation mechanism which will contribute to the gradual gathering of the knowledge.

Ruby on Rails

Ruby on rails is an open source<ref>http://en.wikipedia.org/wiki/Open_source</ref> web application framework provided for Ruby programming language. It is developed by Rails Core Team<ref>http://rubyonrails.org/core</ref> in July 2004. Even though Ruby on Rails is young, it has gained a lot of attention and wined much support from the developers. Another concept, Agile web development<ref>http://blog.bitzesty.com/what-to-expect-from-an-agile-web-development</ref>which can help developers focus on things matters thus adding value to the website and make it better<ref>http://sixrevisions.com/web-development/agile/</ref>, is presented within the Rails community. Rails provides developers a framework which gives structure for all the code they write. The rails framework helps developers build applications and websites in an easy way because it simplifies and abstracts common repetitive tasks <ref>http://blog.bitzesty.com/what-is-ruby-on-rails-and-why-should-i-use-it</ref>.

Framework

Framework is a set of programs and/or code library that helps developer write most of the applications. By using a framework, it will facilitate the development process of the developers and make the developers pay more attention to the specific things they want. Another advantage of framework is it can enable to tie a bunch of discrete components together into something more useful and powerful<ref>http://www.codeproject.com/KB/architecture/WhatIsAFramework.aspx</ref>.

Introduction to MVC framework

The Model-View-Controller (MVC) principle divides the work of an application into three separate but closely cooperative subsystems. MVC divide the business logic into a Model layer and the view logic into a View layer. The Controller interacts with the Model and passes the required data to the View. A Pictorial Diagram of Ruby on Rails framework’s working mechanism is given here<ref>http://www.oracle.com/technetwork/articles/javase/mvc-136693.html</ref>:

Model (ActiveRecord)

View (ActionView)

  • View renders and represents the data in a particular format. View is implemented in ActionView library which is an erb based system for defining presentation templates for data presentation<ref> http://obsforandroid.wordpress.com/2011/06/24/ruby-on-rails-mvc-framework/ </ref>.
  • Every web application should use view to do the interaction between the user and server and display what an authorized user wants to see.

Controller (ActionController)

  • Controller is implemented in ActionController which is a bridge between the view and the model governing the data flow within the application.
  • Controllers should be light to just perform as a mediator or just retrieve the data from database which is to be passed to view to show.
  • In short, the Controller processes input from the View and communicates with Model objects<ref>http://www.converttolinux.com/ruby.shtml</ref>.

Practical Example

One example of MVC framework is to build a Rails application. As with many web frameworks, Rails uses the MVC compound design pattern to solve this problem. MVC splits the business logic into a “Model” layer and the view logic into a “View” layer. The “Controller” interacts with the Model and passes the required data onto the View. A full HTTP request cycle can be simplified into the following steps<ref>http://sixrevisions.com/web-development/four-ways-ruby-on-rails-can-help-you/</ref>:

500px‎

  • The user sends an HTTP request by typing the requested URL into the browser. This request is routed to a specific method in the controller specified by the statements in routes.rb(In the entry: config).
  • The method, being executed on the controller, interacts with the required model, which usually retrieves some data from the database.
  • The controller then passes control to the view which specifies which HTML page should be rendered and makes use of any data passed by the controller.
  • Then the response from the HTML is passed back to the users browser.

Cookbook Application

This part is written based on the class note of Lecture 9<ref>http://courses.ncsu.edu/csc517//common/lectures/notes/lec9.pdf</ref>.

Now we will build a cookbook application to see what in it, and compare the difference among the files in Model, View and Controller. We will also impart some knowledge such as what is <%= yield %> for and how to understand the Edit and Create method in Controller.

Creating a simple cookbook application

We may follow steps below to create a new cookbook application.

500px‎

  • In the Tools- Run Rails Generator, typing scaffold in the pop-up dialog box. In the case of the cookbook application, you can start by generating a scaffolded recipe: this will represent a single recipe

500px‎

  • In the pop-up scaffold dialog box, type recipe title:string description:string instruction:text under the entry Generator arguments.
  • Repeat step 2 to generate a category

500px‎

  • Type category name:string under the entry Generator arguments in the Scaffold dialog box.
  • After scaffolding, we need to run db migrate. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations. By default, when you run the migrations they will create a categories table with a string column, and a recipes table with 2 string columns and a text column.

500px‎

Now we can test if the project is running. Click the green button on the top and type localhost:3000 to find the homepage of our cookbook application where specified in the routes.rb.

Parts in Controller

The controller receives and translates input to requests on the model or view. The controllers are typically responsible for calling methods on the model that change the state of the model. In an active model, this state change is then reflected in the view via the change propagation mechanism. In the passive model, the controller is responsible for telling the view when to update.

Problems and Solutions

Problem1: In general, we want our web applications to keep their information in a relational database. Although it is easy to think from a conceptual point of view, it is difficult to combine relational databases with object-oriented(OO) programming languages<ref>http://download.oracle.com/javase/tutorial/java/concepts/</ref><ref>http://www.orm.net/</ref>. Objects are all about data and operations, and databases are all about sets of values, Operations that are easy to express in relational terms are sometimes difficult to code in an OO system.

Solution1:

  • In rails, it uses ORM<ref>http://en.wikipedia.org/wiki/Object-relational_mapping</ref> libraries map database tables to classes. If in our database there is a table called recipes, our program will have a class named Recipe. Rows in this table correspond to the objects of the class<ref>Agile Web Development with Rails Fourth Editon. Author :Sam Ruby, Dave Thomas, David Heinemeier Hansson</ref>. Within the particular object, attributes are used to get and set the individual columns.
  • The Rails classes that wrap our database tables provide a set of class-level methods that perform table-level operations.
  • Active Record<ref>http://ar.rubyonrails.org/</ref><ref>http://api.rubyonrails.org/classes/ActiveRecord/Base.html</ref> is the ORM layer supplied with Rails. It follows the standard ORM model: tables map to classes, rows to objects, and columns to object attributes.

If we want to find the category with a particular id, in ruby code, it looks like this as in method show in category controller: @category = Category.find(params[:id]) The find method does a database access. This illustrates two common features of Active Record calls.

  • params is an object that holds all of the parameters passed in a browser request.
  • params[:id] holds the id, or primary key, of the object.

We can also see the : @categories = Category.all in method index in category_controller. The all method is to retrieve all records from the Category table and assign the collection to a variable called @categories which later will be passed to View to show the category.

Problem2: What is the difference between new and create method in category_controller?

Solution2: The new method prepares the form for display and is called first; the create method processes the data that was entered and attempts to save it to the db.

Problem3: What is the difference between edit and update in category_controller?

Solution3: Edit retrieves a table entry and displays it in a window. When the changes are submitted, update is invoked.

How does Controller Work?

  • The routes.rb determins the page where the welcome page should be. Before the last statement : match ':controller(/:action(/:id(.:format)))', just add root :to => 'categories#index'. And the category_controller’s method index will retrieve the data from the database and pass it to the view to show. So controllers is just acted as a bridge between the model and the view.

When user clicks any links, it will first notify the Controller the action the user perform and if the data needed to get from the database, then the controller will communicate with the model to retrieve the data and then pass it to the view to show.

Parts in Model

The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

The model encapsulates the functional core of an application, its Domain Logic. The goal of MVC is to make the model independent of the view and controller which together form the user interface of the application. An object may act as the model for more than one MVC triad at a time. Since the model must be independent, it cannot refer to either the view or controller portions of the application. The model may not hold direct instance variables that refer to the view or the controller. It passively supplies its services and data to the other layers of the application.<ref>http://www.phpwact.org/pattern/model_view_controller</ref>

Models contain the relationships and validations.

The relationships may be:

• one-to-one (e.g. a university has a chancellor and a chancellor belongs to one university)

	
class Chancellor < ActiveRecord::Base
      belongs_to :university
      #...
end
class University < ActiveRecord::Base
      has_one :chancellor
      #...
end

• one-to-many(e.g. a course has many sections)

class Section < ActiveRecord::Base
      belongs_to :course
      #...
end
class Course < ActiveRecord::Base
      has_many :sections
      #...
end

• many-to-many(e.g. a course has many professors, professors have many courses)

class Course < ActiveRecord::Base
      has_and_belongs_to_many :professors
      #...
end
	
class Professor < ActiveRecord:: Base
      has_and_belongs_to_many :course
      #...
end

Rails includes methods to help you validate the data that you send to models. If we want to make sure that each field is not blank (eg, in category), we can use validation in model category:

class Category < ActiveRecord::Base
      validates :title,  :presence => true
      validates :description, :presence => true
      validates :instruction, :presence => true
      #...
end

This will ensure that all categories have a title, a description and an instruction. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects.

Parts in View

The view obtains data from the model and presents the output of the application to the uses. The view generally have free access to the model, but should not change the state of the model. Views are read only representations of the state of the model. The view reads data from the model using query methods provided by the model. With an Active model, the view can register itself to receive notifications when the model changes, and the view can then present a more up to date version of the model. Sometimes generic reusable view components can be arbitrarily connected to the model in a process known as binding.


edit.html.erb

<h1>Editing category</h1> <%= render 'form' %>
<%= link_to 'Show', @category %> | <%= link_to 'Back', categories_path %>

The form refers to a partial named _form.html.erb. The reason for having partials in Rails is to stick to the Don't Repeat Yourself principle. With partial, we can move the code for rendering a particular piece of a response to its own file so modularity can be achieved.


_form.html.erb in category

<%= form_for(@category) do |f| %> 
    <% if @category.errors.any? %> 
        <div id="error_explanation">
             <h2><%= pluralize(@category.errors.count, "error") %> prohibited this category from being saved:</h2>
             <ul> 
             <% @category.errors.full_messages.each do |msg| %>
                  <li><%= msg %></li> 
             <% end %> 
             </ul>
             </div> 
         <% end %>
         <div class="field"> 
            <%= f.label :name %><br /> 
            <%= f.text_field :name %>
         </div> 
         <div class="actions">
            <%= f.submit %> 
         </div>
      <% end %>


_form.html.erb in recipe

<%= form_for(@recipe) do |f| %>
  <% if @recipe.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>

      <ul>
      <% @recipe.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :category %><br />
    <%= select("recipe", "category_id", Category.find(:all).collect{ |c| [ c.name, c.id] }) %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </div>
  <div class="field">
    <%= f.label :instructions %><br />
    <%= f.text_area :instructions %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

The difference in the _form.html.erb files for categories and recipes is the _form.html.erb for recipes handles more data from response of recipes.url than categories hence its bigger than that for categories.


In this application, if we add the code below in the show.html.erb file under category folder, then in the page of category#show, we can see two links, which are "Edit" and "Back", and by clicking these two links, we can be redirected to the edit category page and the category page with all listed categories.

<%= link_to 'Edit', edit_category_path(@category) %>
<%= link_to 'Back', categories_path %>
  • We may find that <%= yield %> in application.html.erb and yield identifies a section where content from the view should be inserted. In this case, we will see the page where the routes.rb specified.
  • The “recipes_url”, “categories_url” will link to the urls pertaining to recipes and categories which will correspondingly show the recipe and category.


Conclusion

In this article, some basic knowledge about Ruby on Rails, framework and MVC is introduced. In addition, the article provides some important knowledge about Ruby on Rails through building the cookbook application, and solves some problems that readers may encounter. After reading this article, readers may learn some preliminary knowledge about the MVC, Ruby on Rails, framework and how the model, view and controller communicating with each other as a unit, thus be able to develop web applications using Ruby on Rails.

References

<references/>