Ruby on Rails 2.1 – Resources

Ruby on Rails 2.1 – Resources ”; Previous Next The following resources contain additional information on Ruby on Rails 2.1. Please use them to get more in-depth knowledge on this topic. Learn Ruby on Rails online from Scratch 47 Lectures 9.5 hours Eduonix Learning Solutions More Detail Ruby on Rails Course for Beginners 98 Lectures 7.5 hours Skillbakery More Detail Dissecting Ruby on Rails 5 – Become a Professional Developer 228 Lectures 40 hours YouAccel More Detail Print Page Previous Next Advertisements ”;

Quick Reference Guide

Ruby on Rails 2.1 – Quick Guide Reference ”; Previous Next Here we have listed all the important functions, scripts, validations, etc. Ruby on Rails – Rake Utility Ruby on Rails – The Scripts Ruby on Rails – The Plugins Ruby on Rails – The Generators Ruby on Rails – Model Relations Ruby on Rails – Controller Methods Ruby on Rails – Layouts Ruby on Rails – Render Ruby on Rails – HTML Forms Ruby on Rails – RXML Ruby on Rails – RHTML Ruby on Rails – HTML Links Ruby on Rails – Session and Cookies Ruby on Rails – User Input Validations Ruby on Rails – Maths Functions Ruby on Rails – Finders Ruby on Rails – Nested with-scope Ruby on Rails – Callback Functions Print Page Previous Next Advertisements ”;

Rails 2.1 Layouts

Ruby on Rails 2.1 – Layouts ”; Previous Next A layout defines the surroundings of an HTML page. It”s the place to define the common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and is available for use. First, let”s create the template. Add a new file called standard.rhtml to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a same naming same is advised. Add the following code to the new standard.rhtml file and save your changes − <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <meta http-equiv=”Content-Type” content=”text/html;. charset=iso-8859-1″ /> <meta http-equiv=”Content-Language” content=”en-us” /> <title>Library Info System</title> <%= stylesheet_link_tag “style” %> </head> <body id=”library”> <div id=”container”> <div id=”header”> <h1>Library Info System</h1> <h3>Library powered by Ruby on Rails</h3> </div> <div id=”content”> <%= yield -%> </div> <div id=”sidebar”></div> </div> </body> </html> Everything you just added are standard HTML elements except the two lines with the stylesheet_link_tag helper method that outputs a stylesheet <link>. In this instance, we are linking the style.css stylesheet. The yield command lets Rails know that it should put the RHTML for the method called here. Now open book_controller.rb and add the following line just below the first line − class BookController < ApplicationController layout ”standard” def list @books = Book.find(:all) end ………………. It directs the controller that we want to use a layout available in the standard.rhtml file. Now, try browsing books that will produce the following screen. Adding a Stylesheet Till now, we have not created any stylesheet, so Rails is using the default stylesheet. Now, let”s create a new file called style.css and save it in /public/stylesheets. Add the following code to this file. body { font-family: Helvetica, Geneva, Arial, sans-serif; font-size: small; font-color: #000; background-color: #fff; } a:link, a:active, a:visited { color: #CD0000; } input { margin-bottom: 5px; } p { line-height: 150%; } div#container { width: 760px; margin: 0 auto; } div#header { text-align: center; padding-bottom: 15px; } div#content { float: left; width: 450px; padding: 10px; } div#content h3 { margin-top: 15px; } ul#books { list-style-type: none; } ul#books li { line-height: 140%; } div#sidebar { width: 200px; margin-left: 480px; } ul#subjects { width: 700px; text-align: center; padding: 5px; background-color: #ececec; border: 1px solid #ccc; margin-bottom: 20px; } ul#subjects li { display: inline; padding-left: 5px; } Now, refresh your browser and see the difference − What is Next? The next chapter explains how to develop applications with Rails Scaffolding to give user access to add, delete, and modify the records in any database. Print Page Previous Next Advertisements ”;

Rails 2.1 RMagick Guide

Ruby on Rails 2.1 – RMagick Guide ”; Previous Next Rails provides bindings to ImageMagick and GraphicsMagick, which are popular and stable C libraries. The RMagick library provides the same interface against ImageMagick and GraphicsMagick, so it does not matter which one you use. You can get RMagick by installing the rmagick gen on Unix or rmagick-win32 gem on Windows. Let”s install it on a Unix machine as follows − $ gem install rmagick The RMagick module comes along with class Magick::Image, which lets you resize images in four different methods − resize(width, height) scale(width, height) sample(width, height) thumbnail(width, height) All these methods accept a pair integer values, corresponding to the width and height in pixels of the thumbnail you want. Example Here”s an example that uses resize() method to resize the image. It takes the file tmp.jpg and makes a thumbnail of it 100 pixels wide by 100 pixels tall − require ”rubygems” require ”RMagick” class ImageController < ApplicationController def createThubnail width, height = 100, 100 img = Magick::Image.read(”tmp.jpg”).first thumb = img.resize(width, height) # If you want to save this image use following # thumb.write(“mythumbnail.jpg”) # otherwise send it to the browser as follows send_data(thumb.to_blob, :disposition => ”inline”, :type => ”image/jpg”) end end Here are the steps to create a thumbnail − Here the class method Image.read receives an image filename as an argument and returns an array of Image objects. You obtain the first element of that array, which is obviously our tmp.jpg image. Next, we are calling method resize with the desired arguments, which is creating a thumbnail. Finally, we are directing this image to the browser. You can also use the method thumb.write(“mythumbnail.jpg”) to store this image locally at your machine. Converting Image Formats It is very easy to convert an image file from one format to another format. RMagick handles it very smartly. You can just read in the file and write it out with a different extension. Example The following example converts a JPEG file into a GIF file − require ”rubygems” require ”RMagick” class ImageController < ApplicationController def changeFormat img = Magick::Image.read(”tmp.jpg”).first # If you want to save this image use following # img.write(“mythumbnail.gif”) # otherwise send it to the browser as follows send_data(img.to_blob, :disposition => ”inline”, :type => ”image/gif”) end end You can change an image to a format based on your requirement as follows − img = Magick::Image.read(“tmp.png”).first img.write(“tmp.jpg”) # Converts into JPEG img.write(“tmp.gif”) # Converts into GIF img.write(“JPG:tmp”) # Converts into JPEG img.write(“GIF:tmp”) # Converts into GIF Print Page Previous Next Advertisements ”;

Rails 2.1 Controllers

Ruby on Rails 2.1 – Controllers ”; 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 − C:rubylibrary> ruby script/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 will have a 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 us 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 up to 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’s implement all the methods one by one. Implementing the list Method The list method gives you a printout of all the books in the database. This functionality will be achieved by the following lines of code. def list @books = Book.find(:all) end The @books = Book.find(: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 @books = 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 the 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. Just add the following code in this method. def new @book = Book.new @subjects = Subject.find(:all) end The above method will be called when you will display a page to the user to take user input. Here the second line grabs all the subjects from the database and puts them in an array called @subjects. Implementing the create Method Once you take the 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(params[:book]) if @book.save redirect_to :action => ”list” else @subjects = Subject.find(:all) render :action => ”new” end end The first line creates a new instance variable called @book that holds a Book object built from the data the user submitted. 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 and it automatically forwards you to your destination without any user interaction. Then @subjects = Subject.find(: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.find(: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 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(params[:book]) redirect_to :action => ”show”, :id => @book else @subjects = Subject.find(:all) render :action => ”edit” end 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.find(:all) line is required in case it does not save data successfully, then it becomes similar to the edit option. Implementing the delete Method If you want to delete a record in to the database then you will use this

Rails 2.1 Active Records

Ruby on Rails 2.1 – Active Records Models ”; 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 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. Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straightforward mappings between database tables and application objects. Translating a Domain Model into SQL Translating a domain model into SQL is generally straightforward, as long as you remember that you have to write Rails-friendly SQL. In practical terms, you have to follow certain rules such as − 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 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. C:rubylibrary> ruby script/generate model Book C:rubylibrary> ruby script/generate model Subject 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 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 a 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 in the above example, because one subject can have multiple books. Implementing Validations 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. Open book.rb 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 from entering non-numeric data. Besides the validations mentioned above, there are some 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 ”;

Rails 2.1 Introduction

Ruby on Rails 2.1 – Introduction ”; Previous Next What is Ruby? Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails. Ruby is the successful combination of − Smalltalk”s conceptual elegance, Python”s ease of use and learning, and Perl”s pragmatism. Ruby is A high-level programming language. Interpreted like Perl, Python, Tcl/TK. Object-oriented like Smalltalk, Eiffel, Ada, Java. Why Ruby? Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity − Easy to learn Open source (very liberal license) Rich libraries Very easy to extend Truly object-oriented Less coding with fewer bugs Helpful community Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby − Performance Issues − Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++. Threading model − Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads. Sample Ruby Code Here is a sample Ruby code to print “Hello Ruby”. #!/usr/bin/ruby -w # The Hello Class class Hello # Define constructor for the class def initialize( name ) @name = name.capitalize end # Define a ruby method def salute puts “Hello #{@name}!” end end # Create a new object for Hello class obj = Hello.new(“Ruby”) # Call ruby method obj.salute This will produce the following result − Hello Ruby For a complete understanding on Ruby, please go through our Ruby Tutorial Embedded Ruby Ruby provides a program called ERb (Embedded Ruby), written by Seki Masatoshi. ERb allows you to put Ruby code inside an HTML file. ERb reads along, word for word, and then at a certain point, when it encounters a Ruby code, it starts executing the Ruby code. You need to know only two things to prepare an ERb document − If you want some Ruby code executed, enclose it between <% and %>. If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>. Here”s an example. Save the code in erbdemo.erb file. Note that a Ruby file will have an extension .rb, while an Embeded Ruby file will have an extension .erb. <% page_title = “Demonstration of ERb” %> <% salutation = “Dear programmer,” %> <html> <head> <title>&lt/title> </head> <body> <p>&lt/p> <p>This is an example of how ERb fills out a template.&lt/p> </body> </html> Now, run the program using the command-line utility erb. c:ruby>erb erbdemo.erb This will produce the following result − <html> <head> <title>Demonstration of ERb</title> </head> <body> <p>Dear programmer,</p> <p>This is an example of how ERb fills out a template.&lt/p> </body> </html> What is Rails? An extremely productive web-application framework. You could develop a web application at least ten times faster with Rails, than you could with a typical Java framework. An open source Ruby framework for developing database-backed web applications. Your code and database schema are the configuration! No compilation phase required. Full Stack Framework Includes everything needed to create a database-driven web application using the Model-View-Controller (MVC) pattern. Being a full-stack framework means all the layers are built to work seamlessly with less code. Requires fewer lines of code than other frameworks. Convention over Configuration Rails shuns configuration files in favor of conventions, reflection, and dynamic run-time extensions. Your application code and your running database already contain everything that Rails needs to know! Don”t Repeat Yourself (DRY) DRY is a slogan you will hear frequently associated with Ruby on Rails, which means you need to code the behavior only once and you never have to write similar code in two different places. This is important because you are less likely to make mistakes by modifying your code at one place only. Rails Strengths Rails is packed with features that make you more productive, with many of the following features building on one other. Metaprogramming − Other frameworks use extensive code generation from scratch. Metaprogramming techniques use programs to write programs. Ruby is one of the best languages for metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on metaprogramming for the heavy lifting. Active Record − Rails introduces the Active Record framework, which saves objects to the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming. Convention over configuration − Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn”t need much configuration. Scaffolding − You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you”ll need. Ajax at the core − Ajax is the technology that has become a standard to provide interactivity to websites without becoming intrusive. Ruby on Rails has a great support for Ajax technology and it is a part of the core libraries. So, when you install RoR, Ajax support is also made available to you. Built-in testing − Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility. Three environments − Rails gives you three default environments – development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run. What is Rails 2.1.0? This is the latest version of Ruby on Rails, which has been released by the Rails core team on Saturday May

Rails 2.1 and AJAX

AJAX on Rails 2.1 ”; Previous Next Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following − XHTML for the markup of web pages CSS for the styling Dynamic display and interaction using the DOM Data manipulation and interchange using XML Data retrieval using XMLHttpRequest JavaScript as the glue that meshes all this together Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page. When you interact with an Ajax-powered web page, it loads an Ajax engine in the background. The engine is written in JavaScript and its responsibility is to both communicate with the web server and display the results to the user. When you submit data using an Ajax-powered form, the server returns an HTML fragment that contains the server”s response and displays only the data that is new or changed as opposed to refreshing the entire page. For a complete detail on AJAX you can go through our AJAX Tutorial. How Rails Implements Ajax Rails has a simple, consistent model for how it implements Ajax operations. Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web application) or trigger an Ajax operation − Some trigger fires − This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer). The web client calls the server − A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form The server does processing − The server-side action handler (Rails controller action), does something with the data and returns an HTML fragment to the web client. The client receives the response − The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current page”s HTML, often the content of a <div> tag. These steps are the simplest way to use Ajax in a Rails application, but with a little extra work, you can have the server return any kind of data in response to an Ajax request, and you can create custom JavaScript in the browser to perform more involved interactions. AJAX Example While discussing rest of the Rails concepts, we have taken an example of Library. There we have a table called subject and we had added few subjects at the time of Migration. Till now we have not provided any procedure to add and delete subjects in this table. In this example, we will provide, list, show and create operations on subject table. If you don”t have any understanding on Library Info System explained in the previous chapters, then we would suggest you to complete the previous chapters first and then continue with AJAX on Rails. Creating Controller Let’s create a controller for subject. It will be done as follows − C:rubylibrary> ruby script/generate controller Subject This command creates a controller file app/controllers/subject_controller.rb. Open this file in any text editor and modify it to have the following content − class SubjectController < ApplicationController layout ”standard” def list end def show end def create end end Now, we will discuss the implementation part of all these functions in the same way we had given in the previous chapters. The list Method Implementation def list @subjects = Subject.find(:all) end This is similar to the example explained earlier and will be used to list down all the subjects available in our database. The show Method Implementation def show @subject = Subject.find(params[:id]) end This is also similar to the example explained earlier and will be used to display a particular subject corresponding to the passed ID. The create Method Implementation def create @subject = Subject.new(params[:subject]) if @subject.save render :partial => ”subject”, :object => @subject end end This part is a bit new. Here we are not redirecting the page to any other page; we are just rendering the changed part instead of whole page. It happens only when using partial. We don”t write the complete view file, instead, we will write a partial in the /app/view/subject directory. We will see it in a moment. First, let”s create view files for other methods. Creating Views Now we will create view files for all the methods except for create method for which we will create a partial. Creating View for list Method Create a file list.rhtml in /app/view/subject and populate it with the following code. <h1>Listing Subjects</h1> <ul id=”subject_list”> <% @subjects.each do |c| %> <li><%= link_to c.name, :action => ”show”, :id => c.id %> <%= “(#{c.books.count})” -%></li> <% end %> </ul> Here, you are iterating through the @subjects array and outputting a <li> element containing a link to the subject it is referencing for each item in the array. Additionally, you are outputting the number of books in that specific subject inside parentheses. Rails” associations make it easy to step through a relationship and get information like this. Now, try browsing your Subject list using http://localhost:3000/subject/list. It will show you the following screen. Creating View for show Method Create a file show.rhtml in /app/view/subject and populate it with the following code. <h1><%= @subject.name -%></h1> <ul> <% @subject.books.each do |c| %> <%= link_to c.title, :controller => “book”, :action => “show”,:id => c.id -%> <% end %> </ul> Now, try clicking on any subject and you will find a listing of all the books available under that subject. Creating View for create Method

Ruby on Rails 2.1 – Discussion

Discuss Ruby on Rails 2.1 ”; Previous Next Ruby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson. This tutorial gives you a complete understanding on Ruby on Rails 2.1. Print Page Previous Next Advertisements ”;

Rails 2.1 Tips & Tricks

Ruby on Rails 2.1 – Tips and Tricks ”; Previous Next I”m in process of building a list of good Tips and Tricks received from different Rails Developers. Till the date I could recive only few which I”m going to list down here. If you have any write-up on Ruby on Rails, then please send it to me at [email protected] and I will share it with the world using this section. Ruby on Rails 2.1 – RMagick Rails 2.1 – HTTP Basic Authentication Exception Handling in Ruby on Rails Understanding Routes in Rails 2.1 Print Page Previous Next Advertisements ”;