Ruby on Rails – Active Records ”; Previous Next Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows − tables map to classes, rows map to objects and columns map to object attributes. Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables. Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straight forward mappings between database tables and application objects. Translating a Domain Model into SQL Translating a domain model into SQL is generally straight forward, as long as you remember that you have to write Rails-friendly SQL. In practical terms, you have to follow certain rules − Each entity (such as book) gets a table in the database named after it, but in the plural (books). Each such entity-matching table has a field called id, which contains a unique integer for each record inserted into the table. Given entity x and entity y, if entity y belongs to entity x, then table y has a field called x_id. The bulk of the fields in any table store the values for that entity”s simple properties (anything that”s a number or a string). Creating Active Record Files (Models) To create the Active Record files for our entities for library application, introduced in the previous chapter, issue the following command from the top level of the application directory. library> rails script/generate model Book library> rails script/generate model Subject Above rails generate model book commands generates the auto code as below − You”re telling the generator to create models called Book and Subject to store instances of books and subjects. Notice that you are capitalizing Book and Subject and using the singular form. This is a Rails paradigm that you should follow each time you create a model. When you use the generate tool, Rails creates the actual model file that holds all the methods unique to the model and the business rules you define, a unit test file for performing test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration that makes creating database tables and columns easy. Apart from creating many other files and directories, this will create files named book.rb and subject.rb containing a skeleton definition in the app/models directory. Content available in book.rb − class Book < ActiveRecord::Base end Content available in subject.rb − class Subject < ActiveRecord::Base end Creating Associations between Models When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations − one-to-one − A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner. one-to-many − A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books. many-to-many − A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object. You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many. Now, you need to tell Rails what relationships you want to establish within the library data system. To do so, modify book.rb and subject.rb to look like this − class Book < ActiveRecord::Base belongs_to :subject end We have used a singular subject in the above example, because one Book can belong to a single Subject. class Subject < ActiveRecord::Base has_many :books end We have used plural books here, because one subject can have multiple books. Implementing Validations on Models The implementation of validations is done in a Rails model. The data you are entering into the database is defined in the actual Rails model, so it only makes sense to define what valid data entails in the same location. The validations are − The value of title field should not be NULL. The value of price field should be numeric. Open book.rb in the appmodel subdiractory and put the following validations − class Book < ActiveRecord::Base belongs_to :subject validates_presence_of :title validates_numericality_of :price, :message=>”Error Message” end validates_presence_of − protects “NOT NULL” fields against missing user input. validates_numericality_of − prevents the user, entering non numeric data. Besides the validations mentioned above, there are other common validations. Check Rails Quick Guide. What is Next? In the next chapter, we will learn Rails Migration, which allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. Print Page Previous Next Advertisements ”;
Category: ruby-on-rails
Ruby on Rails – Resources
Ruby on Rails – Useful Resources ”; Previous Next The following resources contain additional information on Ruby on Rails. Please use them to get more in-depth knowledge on this topic. Useful Links on Ruby on Rails Main Ruby Site − Official Ruby site. Find a complete list of all documentation, tutorials, news etc. Ruby Documentation − Ruby documentation site. RubyForge − Open source project repository. Ruby on Rails − Official site for Ruby on Rails. RubyGems − Download link for RubyGem and other documentation. Rails APIs − A comprehensive list of Rails APIs Rails Conf − RailsConf, co-presented by Ruby Central, Inc. and O”Reilly Media, Inc., is the largest official conference dedicated to everything Rails. Ruby Central − Ruby Central, Inc., is a 501(c)(3) tax-exempt organization, dedicated to Ruby support and advocacy. Useful Books on Ruby on Rails To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Ruby on Rails – File Uploading ”; Previous Next You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now we will proceed with a simple and small Rails project. As usual, let”s start off with a new Rails application called testfile. Let”s create the basic structure of the application by using simple rails command. tp> rails new testfile Before starting application development, we should install gem files as shown below − gem install carrierwave gem install bootstrap-sass Open up your gemfile and add the following two gems at the bottom as shown in the following image − After adding gems in the gem file, we need to run the following command on the console − bundle install Creating the Model We need to create a model with two strings as name and attachment as shown below − rails g model Resume name:string attachment:string We need to create the database migration as shown below − rake db:migrate We need to generate the controller as shown below − rails g controller Resumes index new create destroy Great! Now we have the basic structure set up. Now we need to create an uploader. An Uploader came from carrierwave gem and it tells to carrierwave how to handle the files. In short, it contained all file processing functionalities. Run the command to create an uploader as shown below rails g uploader attachment Now open the resume model and call the uploader as shown below. Resume model has placed at app/models/resume.rb − class Resume < ActiveRecord::Base mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model. validates :name, presence: true # Make sure the owner”s name is present. end Before working on controller, we need to modify our config/routes.db as shown below − CarrierWaveExample::Application.routes.draw do resources :resumes, only: [:index, :new, :create, :destroy] root “resumes#index” end Lets us edit the controller as shown below. class ResumesController < ApplicationController def index @resumes = Resume.all end def new @resume = Resume.new end def create @resume = Resume.new(resume_params) if @resume.save redirect_to resumes_path, notice: “The resume #{@resume.name} has been uploaded.” else render “new” end end def destroy @resume = Resume.find(params[:id]) @resume.destroy redirect_to resumes_path, notice: “The resume #{@resume.name} has been deleted.” end private def resume_params params.require(:resume).permit(:name, :attachment) end end Let”s add bootstrap implementation in css file.css file could be in app/assets/stylesheets/resumes.css.scss @import “bootstrap”; Now open up app/views/layouts/application.html.erb and add codes as shown below − <!DOCTYPE html> <html> <head> <title>Tutorialspoint</title> <%= stylesheet_link_tag “application”, media: “all”, “data-turbolinks-track” => true %> <%= javascript_include_tag “application”, “data-turbolinks-track” => true %> <%= csrf_meta_tags %> </head> <body> <div class = “container” style = “padding-top:20px;”> <%= yield %> </div> </body> </html> Now we need to set up index views as shown below − <% if !flash[:notice].blank? %> <div class = “alert alert-info”> <%= flash[:notice] %> </div> <% end %> <br /> <%= link_to “New Resume”, new_resume_path, class: “btn btn-primary” %> <br /> <br /> <table class = “table table-bordered table-striped”> <thead>. <tr> <th>Name</th> <th>Download Link</th> <th> </th> </tr> </thead> <tbody> <% @resumes.each do |resume| %> <tr> <td><%= resume.name %></td> <td><%= link_to “Download Resume”, resume.attachment_url %></td> <td><%= button_to “Delete”, resume, method: :delete, class: “btn btn-danger”, confirm: “Are you sure that you wish to delete #{resume.name}?” %></td> </tr> <% end %> </tbody> </table> Now, lets edit new.html.erb and add our form code. <% if [email protected]? %> <div class = “alert alert-error”> <ul> <% @resume.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class = “well”> <%= form_for @resume, html: { multipart: true } do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.label :attachment %> <%= f.file_field :attachment %> <%= f.submit “Save”, class: “btn btn-primary” %> <% end %> </div> Now start the server and visit http://localhost:3000. It will produce a screen similar to as follows − One last thing we need to do is filter the list of allowed filetypes. For that we need add simple code as shown below at app/uploaders/attachment_uploader.rb class AttachmentUploader < CarrierWave::Uploader::Base storage :file def store_dir “uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}” end def extension_white_list %w(pdf doc htm html docx) end end Now start the server and visit http://localhost:3000. Now input a wrong format; it will generate a wrong message as shown below − For a complete detail on File object, you need to go through the Ruby Reference Manual. Print Page Previous Next Advertisements ”;
Ruby on Rails – Scaffolding
Ruby on Rails – Scaffolding ”; Previous Next While you”re developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method. Scaffolding provides more than cheap demo thrills. Here are some benefits − You can quickly get code in front of your users for feedback. You are motivated by faster success. You can learn how Rails works by looking at the generated code. You can use scaffolding as a foundation to jump start your development. Scaffolding Example To understand scaffolding, let”s create a database called cookbook and a table called recipes. Creating an Empty Rails Web Application Open a command window and navigate to where you want to create this cookbook web application. So, run the following command to create a complete directory structure. tp> rails new cookbook Setting up the Database Here is the way to create a database − mysql> create database cookbook; Query OK, 1 row affected (0.01 sec) mysql> grant all privileges on cookbook.* to ”root”@”localhost” identified by ”password”; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) To instruct Rails how to find the database, edit the configuration file cookbookconfigdatabase.yml and change the database name to cookbook. Leave the password empty. When you finish, it should look as follows − development: adapter: mysql database: cookbook username: root password: [password] host: localhost test: adapter: mysql database: cookbook username: root password: [password] host: localhost production: adapter: mysql database: cookbook username: root password: [password] host: localhost Rails lets you run in the development mode, test mode, or production mode, using different databases. This application uses the same database for each. The Generated Scaffold Code With the scaffold action, Rails generates all the code it needs dynamically. By running scaffold as a script, we can get all the code written to disk, where we can investigate it and then start tailoring it to our requirements. So now, let”s start once again to generate Scaffold code manually by using the scaffold helper script − cookbook> rails generate scaffold recipe It generates auto-files as shown below − The Controller Let”s look at the code behind the controller. This code is generated by the scaffold generator. If you open app/controllers/recipes_controller.rb, then you will find something as follows − class RecipesController < ApplicationController before_action :set_recipe, only: [:show, :edit, :update, :destroy] # GET /recipes # GET /recipes.json def index @recipes = Recipe.all end # GET /recipes/1 # GET /recipes/1.json def show end # GET /recipes/new def new @recipe = Recipe.new end # GET /recipes/1/edit def edit end # POST /recipes # POST /recipes.json def create @recipe = Recipe.new(recipe_params) respond_to do |format| if @recipe.save format.html { redirect_to @recipe, notice: ”Recipe was successfully created.” } format.json { render :show, status: :created, location: @recipe } else format.html { render :new } format.json { render json: @recipe.errors, status: :unprocessable_entity } end end end # PATCH/PUT /recipes/1 # PATCH/PUT /recipes/1.json def update respond_to do |format| if @recipe.update(recipe_params) format.html { redirect_to @recipe, notice: ”Recipe was successfully updated.” } format.json { render :show, status: :ok, location: @recipe } else format.html { render :edit } format.json { render json: @recipe.errors, status: :unprocessable_entity } end end end # DELETE /recipes/1 # DELETE /recipes/1.json def destroy @recipe.destroy respond_to do |format| format.html { redirect_to recipes_url, notice: ”Recipe was successfully destroyed.” } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_recipe @recipe = Recipe.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def recipe_params params.require(:recipe).permit(:tittle, :instructions) end end When the user of a Rails application selects an action, e.g. “Show” – the controller will execute any code in the appropriate section – “def show” – and then by default will render a template of the same name – “show.html.erb”. This default behavior can be overwritten. The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables. Note that you do not have to write any SQL statements, rails will take care of it automatically. This single line of code will bring the database table to life. It will provide with a simple interface to your data, and ways of − Creating new entries Editing current entries Viewing current entries Destroying current entries When creating or editing an entry, scaffold will do all the hard work like form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs − Simple text strings Text areas (or large blocks of text) Date selectors Date-time selectors You can use Rails Migrations to create and maintain tables. rake db:migrate RAILS_ENV=development Now, go to the cookbook directory and run the Web Server using the following command − cookbook> rails server Now, open a browser and navigate to http://127.0.0.1:3000/recipe/new. This will provide you a screen to create new entries in the recipes table. A screenshot is shown below − Once you press the Create button to create a new recipe, your record is added into the recipes table and it shows the following result − You can see the option to edit, show, and destroy the records. So, play around with these options. You can also list down all the recipes available in the recipes table using the URL http://127.0.0.1:3000/recipe/list. Enhancing the Model Rails gives you a lot of error handling for free. To understand this, add some validation rules to the empty recipe model − Modify app/models/recipe.rb as follows and then test your application − class Recipe < ActiveRecord::Base validates_length_of :title, :within => 1..20 validates_uniqueness_of :title, :message => “already exists” end These entries will give automatic checking. validates_length_of − the field is not blank and not too long. validates_uniqueness_of − duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here. Alternative Way to Create Scaffolding
Ruby on Rails – Controllers
Ruby on Rails – Controller ”; Previous Next The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well. It manages caching, which can give applications orders-of-magnitude performance boosts. It manages helper modules, which extend the capabilities of the view templates without bulking up their code. It manages sessions, giving users the impression of an ongoing interaction with our applications. The process for creating a controller is very easy, and it”s similar to the process we”ve already used for creating a model. We will create just one controller here − library> rails generate controller Book Notice that you are capitalizing Book and using the singular form. This is a Rails paradigm that you should follow each time you create a controller. This command accomplishes several tasks, of which the following are relevant here − It creates a file called app/controllers/book_controller.rb If you look at book_controller.rb, you will find it as follows − class BookController < ApplicationController end Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb. The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class. You don”t need to worry with the ApplicationController as of yet, so let”s just define a few method stubs in book_controller.rb. Based on your requirement, you could define any number of functions in this file. Modify the file to look like the following and save your changes. Note that it is upto you what name you want to give to these methods, but better to give relevant names. class BookController < ApplicationController def list end def show end def new end def create end def edit end def update end def delete end end Now let us implement all the methods one by one. Implementing the list Method The list method gives you a list of all the books in the database. This functionality will be achieved by the following lines of code. Edit the following lines in book_controller.rb file. def list @books = Book.all end The @books = Book.all line in the list method tells Rails to search the books table and store each row it finds in the @books instance object. Implementing the show Method The show method displays only further details on a single book. This functionality will be achieved by the following lines of code. def show @book = Book.find(params[:id]) end The show method”s @book = Book.find(params[:id]) line tells Rails to find only the book that has the id defined in params[:id]. The params object is a container that enables you to pass values between method calls. For example, when you”re on the page called by the list method, you can click a link for a specific book, and it passes the id of that book via the params object so that show can find the specific book. Implementing the new Method The new method lets Rails know that you will create a new object. So just add the following code in this method. def new @book = Book.new @subjects = Subject.all end The above method will be called when you will display a page to the user to take user input. Here second line grabs all the subjects from the database and puts them in an array called @subjects. Implementing the create Method Once you take user input using HTML form, it is time to create a record into the database. To achieve this, edit the create method in the book_controller.rb to match the following − def create @book = Book.new(book_params) if @book.save redirect_to :action => ”list” else @subjects = Subject.all render :action => ”new” end end def book_params params.require(:books).permit(:title, :price, :subject_id, :description) end The first line creates a new instance variable called @book that holds a Book object built from the data, the user submitted. The book_params method is used to collect all the fields from object :books. The data was passed from the new method to create using the params object. The next line is a conditional statement that redirects the user to the list method if the object saves correctly to the database. If it doesn”t save, the user is sent back to the new method. The redirect_to method is similar to performing a meta refresh on a web page: it automatically forwards you to your destination without any user interaction. Then @subjects = Subject.all is required in case it does not save data successfully and it becomes similar case as with new option. Implementing the edit Method The edit method looks nearly identical to the show method. Both methods are used to retrieve a single object based on its id and display it on a page. The only difference is that the show method is not editable. def edit @book = Book.find(params[:id]) @subjects = Subject.all end This method will be called to display data on the screen to be modified by the user. The second line grabs all the subjects from the database and puts them in an array called @subjects. Implementing the update Method This method will be called after the edit method, when the user modifies a data and wants to update the changes into the database. The update method is similar to the create method and will be used to update existing books in the database. def update @book = Book.find(params[:id]) if @book.update_attributes(book_param) redirect_to :action => ”show”, :id => @book else @subjects = Subject.all render :action => ”edit” end end def book_param params.require(:book).permit(:title, :price, :subject_id, :description) end The update_attributes method is similar to the save method used by create but instead of creating a new row in the database, it overwrites the attributes of the existing row. Then @subjects = Subject.all line is required in case it does not save the data successfully,
Ruby on Rails – Examples
Ruby on Rails – Examples ”; Previous Next In this chapter, we will create a simple but operational online library system for holding and managing the books. This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored − Books, which describes an actual listing. Subject, which is used to group books together. Workflow for Creating Rails Applications A recommended work flow for creating Rails Application is as follows − Use the rails command to create the basic skeleton of the application. Create a database on the PostgreSQL server to hold your data. Configure the application to know where your database is located and the login credentials for it. Create Rails Active Records (Models), because they are the business objects you”ll be working with in your controllers. Generate Migrations that simplify the creating and maintaining of database tables and columns. Write Controller Code to put a life in your application. Create Views to present your data through User Interface. So, let us start with creating our library application. Creating an Empty Rails Web Application Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application. Go into ruby installation directory to create your application. Run the following command to create a skeleton for library application. It will create the directory structure in the current directory. tp> rails new library This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail. Most of our development work will be creating and editing files in the library/app subdirectories. Here”s a quick run down of how to use them − The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user. The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user”s browser. The models subdirectory holds the classes that model and wrap the data stored in our application”s database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple. The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered. Starting Web Server Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let”s start this web server and then browse to our empty library application − This server will be started from the application directory as follows. It runs on port number 3000. tp> cd rubylibrary tprubylibrary> Rails server It generates the auto code to start the server as shown below − This will start your WEBrick web server. Now open your browser and browse to http://127.0.0.1:3000. If everything is gone fine, then you should see a greeting message from WEBrick, otherwise there is something wrong with your setting. If everything goes well it will generate the output as follows. What is next? The next chapter explains how to create databases for your application and what is the configuration required to access these created databases. Further, we will see what Rails Migration is and how it is used to maintain database tables. Print Page Previous Next Advertisements ”;
Ruby on Rails – Database Setup ”; Previous Next Before starting with this chapter, make sure your database server is up and running. Ruby on Rails recommends to create three databases – a database each for development, testing, and production environment. According to convention, their names should be − library_development library_production library_test You should initialize all three of them and create a user and password for them with full read and write privileges. We are using the root user ID for our application. Database Setup for MySQL In MySQL, we are using the root user ID for our application. The MySQL console session in which you do this looks something like − mysql> create database library_development; Query OK, 1 row affected (0.01 sec) mysql> grant all privileges on library_development.* to ”root”@”localhost” identified by ”password”; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) You can do the same thing for two more databases library_production and library_test. Configuring database.yml At this point, you need to let Rails know about the user name and password for the databases. You do this in the file database.yml, available in the libraryconfig subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the username and password lines to reflect the permissions on the databases you”ve created. When you finish, it should look something like − development: adapter: mysql database: library_development username: root password: [password] host: localhost test: adapter: mysql database: library_test username: root password: [password] host: localhost production: adapter: mysql database: library_production username: root password: [password] host: localhost Database Setup for PostgreSQL By default, PostgreSQL does not provide any users. We have to create new users. Use the following command to create a user with the name rubyuser. tp> sudo -u postgres createuser rubyuser -s If you want to create a password for the new user, then use the following command. tp> sudo -u postgres psql postgres=# password rubyuser Use the following command for creating a database library_development. postgres=# CREATE DATABASE library_development OWNER rubyuser; CREATE DATABASE Use the following command for creating a database library_production. postgres=# CREATE DATABASE library_production OWNER rubyuser; CREATE DATABASE Use the following command for creating a database library_test. postgres=# CREATE DATABASE library_test OWNER rubyuser; CREATE DATABASE Press Ctrl+D to terminate PosgreSQL. Configuring database.yml At this point, you need to let Rails know the username and password for the databases. You do this in the file database.yml, available in the libraryconfig subdirectory of Rails Application you created. This file has live configuration sections for PostgreSQL databases. In each of the sections, you need to change the username and password lines to reflect the permissions on the databases you”ve created. When you finish, it should look as follows − default: &default adapter: postgresql encoding: unicode development: adapter: postgresql encoding: unicode database: library_development username: rubyuser password: <Password for rubyuser> test: adapter: postgresql encoding: unicode database: library_test username: rubyuser password: <Password for rubyuser> production: adapter: postgresql encoding: unicode database: library_production username: rubyuser password: <Password for rubyuser> What is Next? The next two chapters explain how to model your database tables and how to manage those using Rails Migrations. Print Page Previous Next Advertisements ”;
Ruby on Rails – Framework
Ruby on Rails – Framework ”; Previous Next A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want. When you set out to write a Rails application, leaving aside the configuration and other housekeeping chores, you have to perform three primary tasks − Describe and model your application”s domain − The domain is the universe of your application. The domain may be a music store, a university, a dating service, an address book, or a hardware inventory. So here you have to figure out what”s in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling a database structure to keep the entities and their relationship. Specify what can happen in this domain − The domain model is static; you have to make it dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in. Choose and design the publicly available views of the domain − At this point, you can start thinking in Web-browser terms. Once you”ve decided that your domain has students, and that they can register for classes, you can envision a welcome page, a registration page, and a confirmation page, etc. Each of these pages, or views, shows the user how things stand at a certain point. Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework. Ruby on Rails MVC Framework The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems. Model (ActiveRecord ) It maintains the relationship between the objects and the database and handles validation, association, transactions, and more. This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables. View ( ActionView ) It is a presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate with AJAX technology. This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view. Controller ( ActionController ) The facility within the application that directs traffic, on the one hand, querying the models for specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view. This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine). Pictorial Representation of MVC Framework Given below is a pictorial representation of Ruby on Rails Framework − Directory Representation of MVC Framework Assuming a standard, default installation over Linux, you can find them like this − tp> cd /usr/local/lib/ruby/gems/2.2.0/gems tp> ls You will see subdirectories including (but not limited to) the following − actionpack-x.y.z activerecord-x.y.z rails-x.y.z Over a windows installation, you can find them like this − tp>cd rubylibrubygems2.2.0gems rubylibrubygems2.2.0gems>dir You will see subdirectories including (but not limited to) the following − ActionView and ActionController are bundled together under ActionPack. ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provides facilities for manipulating and displaying that data. Rails ties it all together. Print Page Previous Next Advertisements ”;
Ruby on Rails – Directory Structure ”; Previous Next When you use the Rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don”t have to provide any input. Here is a top-level view of a directory tree created by the helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project”s organization. To understand this directory structure, let”s use the demo application created in the Installation chapter. It can be created using a simple helper command rails demo. Now, go into the demo application root directory as follows − tp> cd demo demo> dir You will find a directory structure in Windows as follows − Now let”s explain the purpose of each directory app − It organizes your application components. It”s got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models). app/controllers − The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user. app/helpers − The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered. app/models − The models subdirectory holds the classes that model and wrap the data stored in our application”s database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple! app/view − The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user”s browser. app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout. components − This directory holds components, tiny self-contained applications that bundle model, view, and controller. config − This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory. db − Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory. doc − Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation. lib − You”ll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries). log − Error logs go here. Rails creates scripts that help you manage various error logs. You”ll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log). public − Like the public directory for a web server, this directory has web files that don”t change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public). script − This directory holds scripts to launch and manage the various tools that you”ll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server). test − The tests you write and those that Rails creates for you, all goes here. You”ll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional). tmp − Rails uses this directory to hold temporary files for intermediate processing. vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here. Apart from these directories, there will be two files available in demo directory. README − This file contains a basic detail about Rail Application and description of the directory structure explained above. Rakefile − This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation. Print Page Previous Next Advertisements ”;
Ruby on Rails – Migrations
Ruby on Rails – Migrations ”; Previous Next Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. This has many uses, including − Teams of developers − If one person makes a schema change, the other developers just need to update, and run “rake migrate”. Production servers − Run “rake migrate” when you roll out a new release to bring the database up to date as well. Multiple machines − If you develop on both a desktop and a laptop, or in more than one location, migrations can help you keep them all synchronized. What Can Rails Migration Do? create_table(name, options) drop_table(name) rename_table(old_name, new_name) add_column(table_name, column_name, type, options) rename_column(table_name, column_name, new_column_name) change_column(table_name, column_name, type, options) remove_column(table_name, column_name) add_index(table_name, column_name, index_type) remove_index(table_name, column_name) Migrations support all the basic data types − The following is the list of data types that migration supports − string − for small data types such as a title. text − for longer pieces of textual data, such as the description. integer − for whole numbers. float − for decimals. datetime and timestamp − store the date and time into a column. date and time − store either the date only or time only. binary − for storing data such as images, audio, or movies. Boolean − for storing true or false values. Valid column options are − The following is the list of valid column options. limit ( :limit => “50” ) default (:default => “blah” ) null (:null => false implies NOT NULL) NOTE − The activities done by Rails Migration can be done using any front-end GUI or directly on SQL prompt, but Rails Migration makes all those activities very easy. See the Rails API for details on these. Create the Migrations Here is the generic syntax for creating a migration − application_dir> rails generate migration table_name This will create the file db/migrate/001_table_name.rb. A migration file contains the basic Ruby syntax that describes the data structure of a database table. NOTE − Before running the migration generator, it is recommended to clean the existing migrations generated by model generators. We will create two migrations corresponding to our three tables − books and subjects. Books migration should be as follows − tp> cd library library> rails generate migration books Above command generates the following code. subject migration should be as follows − tp> cd library library> rails generate migration subjects Above command generates the following code. Notice that you are using lower case for book and subject and plural form while creating migrations. This is a Rails paradigm that you should follow each time you create a Migration. Edit the Code Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. Modify 001_books.rb as follows − The ID column will be created automatically, so don”t do it here as well. class Books < ActiveRecord::Migration def self.up create_table :books do |t| t.column :title, :string, :limit => 32, :null => false t.column :price, :float t.column :subject_id, :integer t.column :description, :text t.column :created_at, :timestamp end end def self.down drop_table :books end end The method self.up is used when migrating to a new version, self.down is used to roll back any changes if needed. At this moment, the above script will be used to create books table. Modify 002_subjects.rb as follows − class Subjects < ActiveRecord::Migration def self.up create_table :subjects do |t| t.column :name, :string end Subject.create :name => “Physics” Subject.create :name => “Mathematics” Subject.create :name => “Chemistry” Subject.create :name => “Psychology” Subject.create :name => “Geography” end def self.down drop_table :subjects end end The above script will be used to create subjects table and will create five records in the subjects table. Run the Migration Now that you have created all the required migration files. It is time to execute them against the database. To do this, go to a command prompt and go to the library directory in which the application is located, and then type rake migrate as follows − library> rake db:migrate This will create a “schema_info” table if it doesn”t exist, which tracks the current version of the database – each new migration will be a new version, and any new migrations will be run until your database is at the current version. Rake is a Ruby build program similar to Unix make program that Rails takes advantage of, to simplify the execution of complex tasks such as updating a database”s structure etc. Running Migrations for Production and Test Databases If you would like to specify what Rails environment to use for the migration, use the RAILS_ENV shell variable. For example − library> export RAILS_ENV = production library> rake db:migrate library> export RAILS_ENV = test library> rake db:migrate library> export RAILS_ENV = development library> rake db:migrate NOTE − In Windows, use “set RAILS_ENV = production” instead of export command. What is Next? Now we have our database and the required tables available. In the two subsequent chapters, we will explore two important components called Controller (ActionController) and View (ActionView). Creating Controllers (Action Controller). Creating Views (Action View). Print Page Previous Next Advertisements ”;