CSC/ECE 517 Fall 2012/ch1b 1w64 nn: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(41 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<big>''' SaaS - 3.12 Controller and views'''</big><br>
<big>''' SaaS - 3.12 Controller and views'''</big><br>


[https://class.coursera.org/saas/lecture/preview/index Coursera] is a technology company that provides free online education by making videos. [https://class.coursera.org/saas/lecture/preview/index SaaS] is one such video series made by University of California, Berkley. This article focuses on the concepts and usage of controllers and views in Rails application which is available as one of the [https://www.youtube.com/watch?v=zy7P0E9gs-E SaaS video] lectures.
[https://class.coursera.org/saas/lecture/preview/index Coursera] is a technology company that provides free online education by making videos. [http://en.wikipedia.org/wiki/Software_as_a_service SaaS] is one such video series made by University of California, Berkley.


==Adding a new controller action to Rails application==
=Introduction=
* Create route in config/routes.rb if needed. Make sure that there is a route that is going to eventually route action, if not create one in routes.rb.
 
*  Add the action method in the appropriate app/controllers/*_controller.rb. You have to add the actual code in other words, the method in the appropriate controler file that will do whatever that action is.
This article focuses on the concepts and usage of controllers and views in [http://en.wikipedia.org/wiki/Ruby_on_Rails Rails] application which is available as one of the [https://www.youtube.com/watch?v=zy7P0E9gs-E SaaS video] lectures. It gives an overview of MVC responsibilities in a Rails application with the main focus on the creation of controllers and views for a specific model.
* Ensure there is something for the action to render in app/views/model/action.html.haml. You have to assure that there is something to the action can render what its all done. Every trip through the controller has to end with returning something and will see that although the most common thing is returning a view whose name matches the controller action, we can also return other things.
 
=MVC responsibilities=
In Rails, applications are broken into three types of components: models, views, and controllers.
 
* '''Model''': Application's state is maintained by models. It not only stores the state of the application in databases but also imposes business rules on that data. It contains methods to get and manipulate data. Different methods are provided by ''ActiveRecord'' to do that [1]. An example is shown below.


==MVC responsibilities==
* Model: methods to get/manipulate data. Different methods are provided by active record to do that.
<pre>
<pre>
Movie.where(...), Movie.find(...)
class Movie < ActiveRecord::Base
  belongs_to :genre 
  has_many :actor 
 
  def find_movie_name(movie_id)
    if movie_id then
      movie = Movie.find_by_id(movie_id)     
      return movie.name     
    end
  end
</pre>
</pre>
*Controller: In [http://en.wikipedia.org/wiki/Representational_state_transfer REST] applications, the controller acts as a middle man to synchronize the communication between model and view. It is responsible for receiving request from the user, getting data from the model and making it available to the view for displaying data to the user. Controllers are also responsible for routing the requests to internal actions. This is done with the help of Helper methods.


* '''Controller''': In [http://en.wikipedia.org/wiki/Representational_state_transfer REST] applications, the controller acts as a middle man to synchronize the communication between model and view. It is responsible for receiving request from the user, getting data from the model and making it available to the view for displaying data to the user. Controllers are also responsible for routing the requests to internal actions. This is facilitated by helper methods [3]. An example is shown below.
<pre>
class MoviesController < ApplicationController
  def show
    @movie = Movie.find(params[:id])
  end
end
</pre>
Here, params is the parameter from the request that is parsed out by the routing subsystem. This contains the id of the movie that the user wants to find which can be fetched by calling Movie.find. In a real application, this is unsafe and must be handled by an exception since ''params[:id]'' can happen to be a non-existing value and will result in an error. Finally the instance variable ''@movie'' in the controller is going to be available to the view.
* '''View''':  Views are responsible for creating response in the browser to display data and allow user interaction [2][3]. In the above example, show is going to display the details of a movie (genre, actors). To select the view for the rendering step, the default action the rails will take is, to find a view whose directory name matches the name of its class which is movies and finally matches the name of that particular action i.e show. Thus the view for the above action can be found in ''app/view/movies/show.html.erb''. Here ERb ( [http://en.wikipedia.org/wiki/Embedded_Ruby Embedded Ruby]) is used to generate dynamic content in Rails application.
=Adding a new controller action to Rails application=
In Rails controller forms the logical center of the application. Controller is essentially a Ruby class is inherited from ''ActionController'' super class [3]. To create a controller, these steps must be followed. 
* Add the action method in the appropriate ''app/controllers/*_controller.rb''. This method will have the actual code to do whatever the action is meant to do. For example,
<pre>
class MoviesController < ApplicationController
  def new
  end
end
</pre>
Here the new function creates an instance of Movies controller.
* Create a route in config/routes.rb. When the application receives a request from the user, it is this route that determines the appropriate controller and action to run. Example of a route in ''routes.rb''
<pre>
match 'movies/new' => 'movies#new'
</pre>
* Ensure there is something for the action to render in ''app/views/model/action.html.erb''. Every trip through the controller has to end with returning something to the view. Even if there is no explicit render at the end of controller, by default, Rails looks for that particular action in the ''app/view/model''. For example, the controller shown below has an index method as follows:
<pre>
<pre>
def show
class MoviesController < ApplicationController
  @movie = Movie.find(params[:id])
  def index
    @movies = Movie.all
  end
end
end
</pre>
The view for this controller will be found in ''app/view/movie/index.html.erb''. It is shown below as follows:
<pre>
<h1>Listing Movies</h1>
<table>
  <tr>
    <th>Title</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
<% @movies.each do |movie| %>
  <tr>
    <td><%= movie.title %></td>
    <td><%= movie.description %></td>
    <td><%= link_to 'Show', movie_path(movie) %></td>
    <td><%= link_to 'Edit', edit_movie_path(movie) %></td>
    <td><%= link_to 'Remove', movie, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>
<br />
<%= link_to 'New movie', new_movie_path %>
</pre>
</pre>


params which is the parameter from the request that work hopefully parsed out for us by the routing subsystem. Let us assume that it is going to contain the id of the movie that we want to find beacause then we can just call movie.find. This is unsafe because in a real application because if params[:id] happens to be a non-existing thing, we will get an error. So in practice, we either use find by id or use exceptions. The instance variables in the controller are going to be available to the view
=URI helpers=
*View:  display data, allow user interaction. In this example Show is going to display the details of a movie (description, rating). To select the view for rendering step, the default action the rails will take is, it will try to find a view whose directory name matches the name of the class and finally matches the name of the action.


==URI helpers==
The routing subsystem that maps the URI to different controller actions also provides helper methods that generates routes in the context of that page. These routes generated by helper classes is used by the user in the views to navigate from one page to another [4]. In the above mentioned example of a view, there are three helper methods used namely, ''movie_path(movie)'', ''edit_movie_path(movie)'', ''new_movie_path''. More examples are shown below in the table.    
Once the user is satisfied looking at page, what does he do? There is no place to click. Also how exactly does the user get to this page?    


{| class="wikitable"
{| class="wikitable"
Line 46: Line 113:
|}
|}


Just like the routing subsystem allows us to map http methods and URI's to different control actions, the same routing subsystem also sets up these helpful methods that will generate the routes in the context of the page. Example when we are looking at the list of all movies index.index.html.haml, somewhere on that page there will be a link whose argument is movie_path with an argument.
The following example illustrates how the helper methods work. Lets consider that the user is looking at the list of all movies ''index.html.erb''. Somewhere on that page there will be a link whose argument is movie_path with an argument.
 
<pre>
<pre>
link_to movie_path(3)
link_to movie_path(3)
</pre>
</pre>
movie_path is the helper that set up and gives back a route to the show action for that movie id. So when the user clicks on it, the URI that is going to be generated is going to be movie/:id with a GET method because its a link. This is how it looks in the actual html.
movie_path is the helper that sets up and gives back a route to the show action for that movie id. So when the user clicks on it, the URI that is going to be generated is going to be ''movie/:id'' with a ''GET'' method because its a link. This is how it looks in the actual html.
<pre>
<pre>
<a href="/movies/3">...</a>
<a href="/movies/3">...</a>
</pre>
</pre>
From here, once the URI is hit, that is going to get looked up in the routing subsystem. /movies/something matches the show action of the movies controller and it will take the wild card thing :id and puts that in params[:id]
 
<pre>
From here, once the URI is hit, the controller looks up for this URI in the routing subsystem. This corresponds to the Restful route ''GET /movies/:id'' which matches the show action of the movies controller. Further it takes '':id'' and stores as ''params[:id]''. With that ''params[:id]'', appropriate controller action is called.
GET /movies/:id
 
{:action=>"show", :controller=>"movies"}
[[File:Helper_methods.gif‎|700 px|thumb|center|Connecting URIs using helper methods]]
params[:id]
 
</pre>
Further the user can return to the list of movies with the help of another URI helper, ''movies_path''. ''movies_path'' with no arguments links to the index action. The line to add on show template is
With that appropriate controller action is called
<pre>
def show
  @movie = Movie.find(params[:id])
end
</pre>
Here the controller action can reasonably expect to find that params[:id] will be whatever this route said that it should match.
===What else can we do?===
We can let the user return a list of all movies. We can use RESTful URI helpers. Here it is the index action. movies_path with no arguments links to the index action. The line to add on show template is
<pre>
<pre>
link_to 'Back to List', movies_path
link_to 'Back to List', movies_path
</pre>
</pre>
Back to List is the text that is click-able and movies_path is a method call.
Here Back to List is the text that is click-able and ''movies_path'' is a method call.
As the app gets more complicate, these mechanism scale very nicely
 
==References==
=Conclusion=
Implementing MVC architecture in Rails application has few advantages. For example it separates models from presentation which in turn helps in implementing better test cases and better UI's for the user [9]. It also separates controller functionality with views which facilitates development of better web interfaces. Also Rails provides an easy way to implement MVC architecture for a user. All these advantages and the fact that MVC can be implemented in an effortless and uncomplicated manner necessitate the use of MVC architecture in Rails application. 
 
=References=
#https://www.youtube.com/watch?v=zy7P0E9gs-E
#https://www.youtube.com/watch?v=zy7P0E9gs-E
#http://guides.rubyonrails.org/
#https://class.coursera.org/saas/lecture/preview/index
#http://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Model-View-Controller
#http://en.wikipedia.org/wiki/Ruby_on_Rails
#http://en.wikipedia.org/wiki/Software_as_a_service
#http://en.wikipedia.org/wiki/Representational_state_transfer
#http://en.wikipedia.org/wiki/Representational_state_transfer
#http://en.wikipedia.org/wiki/Embedded_Ruby
#http://amix.dk/blog/post/19615
=Also see=
#http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
#http://books.google.com/books?id=jMCO096qlRsC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false
#http://pragprog.com/book/rails4/agile-web-development-with-rails
#http://ruby.railstutorial.org/

Latest revision as of 20:14, 12 October 2012

SaaS - 3.12 Controller and views

Coursera is a technology company that provides free online education by making videos. SaaS is one such video series made by University of California, Berkley.

Introduction

This article focuses on the concepts and usage of controllers and views in Rails application which is available as one of the SaaS video lectures. It gives an overview of MVC responsibilities in a Rails application with the main focus on the creation of controllers and views for a specific model.

MVC responsibilities

In Rails, applications are broken into three types of components: models, views, and controllers.

  • Model: Application's state is maintained by models. It not only stores the state of the application in databases but also imposes business rules on that data. It contains methods to get and manipulate data. Different methods are provided by ActiveRecord to do that [1]. An example is shown below.
class Movie < ActiveRecord::Base
  belongs_to :genre  
  has_many :actor  

  def find_movie_name(movie_id)
    if movie_id then
      movie = Movie.find_by_id(movie_id)      
      return movie.name      
    end
  end
  • Controller: In REST applications, the controller acts as a middle man to synchronize the communication between model and view. It is responsible for receiving request from the user, getting data from the model and making it available to the view for displaying data to the user. Controllers are also responsible for routing the requests to internal actions. This is facilitated by helper methods [3]. An example is shown below.
class MoviesController < ApplicationController
  def show
    @movie = Movie.find(params[:id])
  end
end

Here, params is the parameter from the request that is parsed out by the routing subsystem. This contains the id of the movie that the user wants to find which can be fetched by calling Movie.find. In a real application, this is unsafe and must be handled by an exception since params[:id] can happen to be a non-existing value and will result in an error. Finally the instance variable @movie in the controller is going to be available to the view.

  • View: Views are responsible for creating response in the browser to display data and allow user interaction [2][3]. In the above example, show is going to display the details of a movie (genre, actors). To select the view for the rendering step, the default action the rails will take is, to find a view whose directory name matches the name of its class which is movies and finally matches the name of that particular action i.e show. Thus the view for the above action can be found in app/view/movies/show.html.erb. Here ERb ( Embedded Ruby) is used to generate dynamic content in Rails application.

Adding a new controller action to Rails application

In Rails controller forms the logical center of the application. Controller is essentially a Ruby class is inherited from ActionController super class [3]. To create a controller, these steps must be followed.

  • Add the action method in the appropriate app/controllers/*_controller.rb. This method will have the actual code to do whatever the action is meant to do. For example,
class MoviesController < ApplicationController
  def new
  end
end

Here the new function creates an instance of Movies controller.

  • Create a route in config/routes.rb. When the application receives a request from the user, it is this route that determines the appropriate controller and action to run. Example of a route in routes.rb
match 'movies/new' => 'movies#new'
  • Ensure there is something for the action to render in app/views/model/action.html.erb. Every trip through the controller has to end with returning something to the view. Even if there is no explicit render at the end of controller, by default, Rails looks for that particular action in the app/view/model. For example, the controller shown below has an index method as follows:
class MoviesController < ApplicationController
  def index
    @movies = Movie.all
  end
end

The view for this controller will be found in app/view/movie/index.html.erb. It is shown below as follows:

<h1>Listing Movies</h1>
 
<table>
  <tr>
    <th>Title</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>
 
<% @movies.each do |movie| %>
  <tr>
    <td><%= movie.title %></td>
    <td><%= movie.description %></td>
    <td><%= link_to 'Show', movie_path(movie) %></td>
    <td><%= link_to 'Edit', edit_movie_path(movie) %></td>
    <td><%= link_to 'Remove', movie, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>
 
<br />
 
<%= link_to 'New movie', new_movie_path %>

URI helpers

The routing subsystem that maps the URI to different controller actions also provides helper methods that generates routes in the context of that page. These routes generated by helper classes is used by the user in the views to navigate from one page to another [4]. In the above mentioned example of a view, there are three helper methods used namely, movie_path(movie), edit_movie_path(movie), new_movie_path. More examples are shown below in the table.

Helper method URI returned RESTful route Action
movies_path /movies GET /movies index
movies_path /movies POST /movies create
new_movie_path /movies/new GET /movies/new new
edit_movie_path(m) /movies/1/edit GET /movies/:id/edit edit
movie_path(m) /movies/1 GET /movies/:id show
movie_path(m) /movies/1 PUT /movies/:id update
movie_path(m) /movies/1 DELETE /movies/:id destroy

The following example illustrates how the helper methods work. Lets consider that the user is looking at the list of all movies index.html.erb. Somewhere on that page there will be a link whose argument is movie_path with an argument.

link_to movie_path(3)

movie_path is the helper that sets up and gives back a route to the show action for that movie id. So when the user clicks on it, the URI that is going to be generated is going to be movie/:id with a GET method because its a link. This is how it looks in the actual html.

<a href="/movies/3">...</a>

From here, once the URI is hit, the controller looks up for this URI in the routing subsystem. This corresponds to the Restful route GET /movies/:id which matches the show action of the movies controller. Further it takes :id and stores as params[:id]. With that params[:id], appropriate controller action is called.

Connecting URIs using helper methods

Further the user can return to the list of movies with the help of another URI helper, movies_path. movies_path with no arguments links to the index action. The line to add on show template is

link_to 'Back to List', movies_path

Here Back to List is the text that is click-able and movies_path is a method call.

Conclusion

Implementing MVC architecture in Rails application has few advantages. For example it separates models from presentation which in turn helps in implementing better test cases and better UI's for the user [9]. It also separates controller functionality with views which facilitates development of better web interfaces. Also Rails provides an easy way to implement MVC architecture for a user. All these advantages and the fact that MVC can be implemented in an effortless and uncomplicated manner necessitate the use of MVC architecture in Rails application.

References

  1. https://www.youtube.com/watch?v=zy7P0E9gs-E
  2. http://guides.rubyonrails.org/
  3. https://class.coursera.org/saas/lecture/preview/index
  4. http://en.wikibooks.org/wiki/Ruby_on_Rails/Getting_Started/Model-View-Controller
  5. http://en.wikipedia.org/wiki/Ruby_on_Rails
  6. http://en.wikipedia.org/wiki/Software_as_a_service
  7. http://en.wikipedia.org/wiki/Representational_state_transfer
  8. http://en.wikipedia.org/wiki/Embedded_Ruby
  9. http://amix.dk/blog/post/19615

Also see

  1. http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
  2. http://books.google.com/books?id=jMCO096qlRsC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false
  3. http://pragprog.com/book/rails4/agile-web-development-with-rails
  4. http://ruby.railstutorial.org/