Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
852
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
5
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. To develop a web application using Ruby on Rails Framework, install the following software: * Ruby * The Rails framework * A Web Server * A Database System We assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production. Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database. Ruby on Rails Installation
  • 2. 1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then type gem --version. If you don't get an error, skip to step 3. Otherwise, we'll install a fresh Ruby. 2. If Ruby is not installed, then download an installation package from rubyinstaller.rubyforge.org. Follow the download link, and run the resulting installer. This is an exe like ruby186-25.exe and will be installed in a single click. You may as well install everything . It's a very small package, and you'll get RubyGems as well alongwith this package. Please check Release Notes for more detail. 3. With RubyGems loaded, you can install all of Rails and its dependencies through the command line: C:> gem install rails --include-dependencies
  • 3. Architecture of Rails Applications
  • 4. Ruby on Rails MVC framework: The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems. Model Maintains the relationship between Object and Database and handles validation, association, transactions, and more. View 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 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, massaging it) into a form that fits the needs of a given view.
  • 5. Building an 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. 1. Go into ruby installation directory to create your application. 2. Run the following command to create a skeleton for library application. C: uby> rails hello 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
  • 6. Ruby on Rails Directory Structure 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 tell it. Here is a top level view of directory tree created by 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 demo application created in installation chapter. This can be created using a simple helper command C: uby> rails hello Now go into demo application root directory as follows: C: uby> cd hello C: ubyhello> dir
  • 7. You will find a directory structure as follows: demo/ ..../app ......../controller ......../helpers ......../models ......../views ............../layouts ..../components ..../config ..../db ..../doc ..../lib ..../log ..../public ..../script ..../test ..../tmp ..../vendor README Rakefile
  • 8.
    • app : This 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 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.
  • 9. 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.
  • 10. Starting up the Web Server You actually have a functional Rails application already – after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command: script/server This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to http://localhost:3000. You should see Rails’ default information page:
  • 11. Rails Database Setup 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 C: ubylibraryconfig 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.
  • 12.
    • When you finish, it should look something like:
    • development:
      • adapter: mysql
      • database: library_development
      • username: root
      • password: [password]
      • host: localhost
  • 13. 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: * 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.
  • 14. 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: ubylibrary> ruby script/generate model Book C: ubylibrary> 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.
  • 15. Content available in book.rb class Book < ActiveRecord::Base end Content available in subject.rb class Subject < ActiveRecord::Base end
  • 16. Module ActionView::Helpers::FormTagHelper * check_box_tag * file_field_tag * form_tag * hidden_field_tag * image_submit_tag * label_tag * password_field_tag * radio_button_tag * select_tag * submit_tag * text_area_tag * text_field_tag
  • 17. check_box_tag(name, value = &quot;1&quot;, checked = false, options = {}) Options * :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML options for the tag. Creates a check box form input tag. check_box_tag check_box_tag 'accept' # => <input id=&quot;accept&quot; name=&quot;accept&quot; type=&quot;checkbox&quot; value=&quot;1&quot; /> check_box_tag 'rock', 'rock music' # => <input id=&quot;rock&quot; name=&quot;rock&quot; type=&quot;checkbox&quot; value=&quot;rock music&quot; /> Examples
  • 18. Examples file_field_tag(name, options = {}) Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag: <% form_tag '/upload', :multipart => true do %> <label for=&quot;file&quot;>File to Upload</label> <%= file_field_tag &quot;file&quot; %> <%= submit_tag %> <% end %> file_field_tag 'attachment' # => <input id=&quot;attachment&quot; name=&quot;attachment&quot; type=&quot;file&quot; />
  • 19. form_tag(url_for_options = {}, options = {}) Starts a form tag that points the action to an url configured with url_for_options just like ActionController::Base#url_for. The method for the form defaults to POST. Options * :multipart - If set to true, the enctype is set to &quot;multipart/form-data&quot;. * :method - The method to use when submitting the form, usually either &quot;get&quot; or &quot;post&quot;. If &quot;put&quot;, &quot;delete&quot;, or another verb is used, a hidden input with name _method is added to simulate the verb over post. * A list of parameters to feed to the URL the form will be posted to. form_tag('/posts') # => <form action=&quot;/posts&quot; method=&quot;post&quot;> form_tag('/posts/1', :method => :put) # => <form action=&quot;/posts/1&quot; method=&quot;put&quot;> Examples
  • 20. password_field_tag(name = &quot;password&quot;, value = nil, options = {}) Creates a password field, a masked text field that will hide the users input behind a mask character. Options * :disabled - If set to true, the user will not be able to use this input. * :size - The number of visible characters that will fit in the input. * :maxlength - The maximum number of characters that the browser will allow the user to enter. * Any other key creates standard HTML attributes for the tag. password_field_tag 'pass' # => <input id=&quot;pass&quot; name=&quot;pass&quot; type=&quot;password&quot; /> password_field_tag 'secret', 'Your secret here' # => <input id=&quot;secret&quot; name=&quot;secret&quot; type=&quot;password&quot; value=&quot;Your secret here&quot; /> Examples
  • 21. radio_button_tag(name, value, checked = false, options = {}) Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options. Options * :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML options for the tag. Examples radio_button_tag 'gender', 'male' # => <input id=&quot;gender_male&quot; name=&quot;gender&quot; type=&quot;radio&quot; value=&quot;male&quot; /> radio_button_tag 'receive_updates', 'no', true # => <input checked=&quot;checked&quot; id=&quot;receive_updates_no&quot; name=&quot;receive_updates&quot; type=&quot;radio&quot; value=&quot;no&quot; />
  • 22. select_tag(name, option_tags = nil, options = {}) Creates a dropdown selection box, or if the :multiple option is set to true, a multiple choice selection box. Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or associated records. option_tags is a string containing the option tags for the select box. Options * :multiple - If set to true the selection will allow multiple choices. * :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML attributes for the tag.
  • 23. Examples select_tag &quot;people&quot;, &quot;<option>David</option>&quot; # => <select id=&quot;people&quot; name=&quot;people&quot;><option>David</option></select> select_tag &quot;count&quot;, &quot;<option>1</option><option>2</option><option>3</option><option>4</option>&quot; # => <select id=&quot;count&quot; name=&quot;count&quot;><option>1</option><option>2</option> # <option>3</option><option>4</option></select>
  • 24. submit_tag(value = &quot;Save changes&quot;, options = {}) Creates a submit button with the text value as the caption. Options * :confirm => ‘question?‘ - This will add a JavaScript confirm prompt with the question specified. If the user accepts, the form is processed normally, otherwise no action is taken. * :disabled - If true, the user will not be able to use this input. * :disable_with - Value of this parameter will be used as the value for a disabled version of the submit button when the form is submitted. * Any other key creates standard HTML options for the tag. Examples submit_tag # => <input name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Save changes&quot; /> submit_tag &quot;Edit this article&quot; # => <input name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Edit this article&quot; />
  • 25. text_area_tag(name, content = nil, options = {}) Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. Options * :size - A string specifying the dimensions (columns by rows) of the textarea (e.g., &quot;25x10&quot;). * :rows - Specify the number of rows in the textarea * :cols - Specify the number of columns in the textarea * :disabled - If set to true, the user will not be able to use this input. * :escape - By default, the contents of the text input are HTML escaped. If you need unescaped contents, set this to false. * Any other key creates standard HTML attributes for the tag.
  • 26. Examples text_area_tag 'post' # => <textarea id=&quot;post&quot; name=&quot;post&quot;></textarea> text_area_tag 'bio', @user.bio # => <textarea id=&quot;bio&quot; name=&quot;bio&quot;>This is my biography.</textarea> text_area_tag 'body', nil, :rows => 10, :cols => 25 # => <textarea cols=&quot;25&quot; id=&quot;body&quot; name=&quot;body&quot; rows=&quot;10&quot;></textarea>
  • 27. text_field_tag(name, value = nil, options = {}) Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query. Options * :disabled - If set to true, the user will not be able to use this input. * :size - The number of visible characters that will fit in the input. * :maxlength - The maximum number of characters that the browser will allow the user to enter. * Any other key creates standard HTML attributes for the tag. Examples text_field_tag 'name' # => <input id=&quot;name&quot; name=&quot;name&quot; type=&quot;text&quot; /> text_field_tag 'query', 'Enter your search query here' # => <input id=&quot;query&quot; name=&quot;query&quot; type=&quot;text&quot; value=&quot;Enter your search query here&quot; />
  • 28. The Basics, Relationships between Tables Tables and Classes
  • 29. When we create a subclass of ActiveRecord::Base, we’re creating something that wraps a database table. By default, Active Record assumes that the name of the table is the plural form of the name of the class. If the class name contains multiple capitalized words, the table name is assumed to have underscores between these words. Some irregular plurals are handled. class Sheep < ActiveRecord::Base set_table_name &quot;sheep&quot; # Not &quot;sheeps&quot; End class Order < ActiveRecord::Base set_table_name &quot;ord_rev99_x&quot; # Wrap a legacy table... End If you don’t like methods called set_xxx, there’s also a more direct form: class Sheep < ActiveRecord::Base self.table_name = &quot;sheep&quot; end
  • 30. Columns and Attributes Active Record objects correspond to rows in a database table. The objects have attributes corresponding to the columns in the table. You probably noticed that our definition of class Order didn’t mention any of the columns in the orders table. That’s because Active Record determines them dynamically at runtime. Active Record reflects on the schema inside the database to configure the classes that wrap tables. def self.up create_table :orders do |t| t.string :name t.text :address t.string :email t.string :pay_type, :limit => 10 t.timestamps end end
  • 31. So, all we have to do is run the migration: demo> rake db:migrate
  • 32. Relationships between Tables One-to-One Relationships
  • 33. One-to-One Relationships A one-to-one association (or, more accurately, a one-to-zero-or-one relationship) is implemented using a foreign key in one row in one table to reference at most a single row in another table. A one-to-one relationship might exist between orders and invoices: for each order there’s at most one invoice. As the example shows, we declare this in Rails by adding a has_one declaration to the Order model and by adding a belongs_to declaration to the Invoice model. There’s an important rule illustrated here: the model for the table that contains the foreign key always has the belongs to declaration.
  • 34. One-to-Many Relationships
  • 35. One-to-Many Relationships A one-to-many association allows you to represent a collection of objects. For example, an order might have any number of associated line items. In the database, all the line item rows for a particular order contain a foreign key column referring to that order. In Active Record, the parent object (the one that logically contains a collection of child objects) uses has_many to declare its relationship to the child table, and the child table uses belongs_to to indicate its parent. In our example, class LineItem belongs_to :order, and the orders table has_many :line_items. Note that again , because the line item contains the foreign key, it has the belongs_to declaration.
  • 36. Many-to-Many Relationships
  • 37. Many-to-Many Relationships Finally, we might categorize our products. A product can belong to many categories, and each category may contain multiple products. This is an example of a many-to-many relationship. It’s as if each side of the relationship contains a collection of items on the other side. Create, Read, Update, Delete (CRUD ) Active Record makes it easy to implement the four basic database operations: create, read, update, and delete. In this section we’ll be working with our orders table in a MySQL database. The following examples assume we have a basic Active Record model for this table: class Order < ActiveRecord::Base end
  • 38. Creating New Rows In the object-relational paradigm, tables are represented as classes, and rows in the table correspond to objects of that class. It seems reasonable that we create rows in a table by creating new objects of the appropriate class. We can create new objects representing rows in our orders table by calling Order.new. We can then fill in the values of the attributes (corresponding to columns in the database). Finally, we call the object’s save method to store the order back into the database. Without this call, the order would exist only in our local memory.
  • 39. an_order = Order.new an_order.name = &quot;Dave Thomas&quot; an_order.email = &quot;dave@pragprog.com&quot; an_order.address = &quot;123 Main St&quot; an_order.pay_type = &quot;check&quot; an_order.save Active Record constructors take an optional block. If present, the block is invoked with the newly created order as a parameter. This might be useful if you wanted to create and save away an order without creating a new local variable.
  • 40. Reading Existing Rows Reading from a database involves first specifying which particular rows of data you are interested in—you’ll give Active Record some kind of criteria, and it will return objects containing data from the row(s) matching the criteria. The simplest way of finding a row in a table is by specifying its primary key. Every model class supports the find method, which takes one or more primary key values. If given just one primary key, it returns an object containing data for the corresponding row (or throws a RecordNotFound exception). If given multiple primary key values, find returns an array of the corresponding objects. Note that in this case a RecordNotFound exception is raised if any of the ids cannot be found (so if the method returns without raising an error, the lengthof the resulting array will be equal to the number of ids passed as parameters): an_order = Order.find(27) # find the order with id == 27
  • 41. pos = Order.find(:all, :conditions => &quot;name = 'Dave' and pay_type = 'po'&quot; ) Using Like Clauses # get the name from the form name = params[:name] # DON'T DO THIS!!! pos = Order.find(:all, :conditions => &quot;name = '#{name}' and pay_type = 'po'&quot; ) User.find(:all, :conditions => [&quot;name like ?&quot; , params[:name]+&quot;%&quot; ])
  • 42. Writing Our Own SQL The find method constructs the full SQL query string for us. The method find_by_sql lets our application take full control. It accepts a single parameter containing a SQL select statement (or an array containing SQL and placeholder values, as for find) and returns a (potentially empty) array of model orders = Order.find_by_sql(&quot;select name, pay_type from orders&quot; )
  • 43. Getting Column Statistics Rails 1.1 added the ability to perform statistics on the values in a column. For example, given a table of orders, we can calculate the following: average = Order.average(:amount) # average amount of orders max = Order.maximum(:amount) min = Order.minimum(:amount) total = Order.sum(:amount) number = Order.count These all correspond to aggregate functions in the underlying database, but they work in a database-independent manner. If you want to access databasespecific functions, you can use the more general-purpose calculate method. For example, the MySQL std function returns the population standard deviation of an expression