Welcome to my blog!

Thanks for stopping by!

Alaska

Alaska

7/31/12

Rails: Understanding Models, Views and Controllers


Here is how I understand how rails work, high level. And I was able to find this great diagram.



The browser makes a request, such as http://leonidpekker.com/picture/show/13



The web server (mongrel, nginx, unicorn etc.) receives the request. It uses Routing System to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb.
In our case, it’s the “picture” controller, method “show”, id “13″. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters.

Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. They are like a bossy manager who tells their employees what to do. They give orders without knowing (or caring) how it gets done. In our case, the show method in the video controller knows it needs to lookup a picture. It asks the model to get picture 13, and will eventually display it to the user.

Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. In this case, the model retrieves picture 13 from the database.



Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what happens in the back room. In our example, the controller gives picture 13 to the “show” view. The show view generates the HTML: divs, tables, text, descriptions, footers, etc.

The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.
It’s more fun to imagine a story with “fat model, skinny controller” instead of a sterile “3-tiered architecture”. Models do the grunt work, views are the happy face, and controllers are the masterminds behind it all. The web server is the invisible gateway, shuttling data back and forth: users never interact with the controller directly.

Database Interaction:
The code < ActiveRecord::Base means your lovely user model inherits from class ActiveRecord::Base, and gets Rails magic to query and save to a database.
Ruby can also handle “undefined” methods with ease. ActiveRecord allows methods like “find_by_name”, which don’t actually exist. When you call “find_by_name”, Rails handles the “undefined method” call and searches for the “name” field. Assuming the field is in your database, the model will do a query based on the “name” field.


class User < ActiveRecord::Base


No comments:

Post a Comment