SlideShare une entreprise Scribd logo
1  sur  43
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
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:gt; gem install rails --include-dependencies
Architecture of Rails Applications
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.
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
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:ubygt; rails hello Now go into demo application root directory as follows: C:ubygt; cd  hello C:ubyello> dir
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
[object Object],[object Object],[object Object],[object Object],[object Object]
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.
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:
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:ubyibraryonfig 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.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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.
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:ubyibrarygt; ruby script/generate model Book C:ubyibrarygt; 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
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
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
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; />
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
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
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; />
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.
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>
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; />
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.
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>
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; />
The Basics, Relationships between Tables  Tables and Classes
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
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
So, all we have to do is run the migration: demo> rake db:migrate
Relationships between Tables  One-to-One Relationships
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.
One-to-Many Relationships
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.
Many-to-Many Relationships
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
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.
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.
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
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; ])
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; )
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

Contenu connexe

Tendances

.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...Nancy Thomas
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex codeEdwinOstos
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustionsthan sare
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
Request-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppRequest-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppNathalie Steinmetz
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails SiddheshSiddhesh Bhobe
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationRutul Shah
 
Object Oriented Programming with Laravel - Session 2
Object Oriented Programming with Laravel - Session 2Object Oriented Programming with Laravel - Session 2
Object Oriented Programming with Laravel - Session 2Shahrzad Peyman
 
mule salesforce
mule salesforcemule salesforce
mule salesforceF K
 
Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction Tran Hung
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4than sare
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 

Tendances (20)

.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
Lect06 tomcat1
Lect06 tomcat1Lect06 tomcat1
Lect06 tomcat1
 
Introduction to apex code
Introduction to apex codeIntroduction to apex code
Introduction to apex code
 
Share point review qustions
Share point review qustionsShare point review qustions
Share point review qustions
 
Microsoft Azure
Microsoft AzureMicrosoft Azure
Microsoft Azure
 
Asp.net
Asp.netAsp.net
Asp.net
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
Request-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails AppRequest-Response Cycle of Ruby on Rails App
Request-Response Cycle of Ruby on Rails App
 
Intro To Asp
Intro To AspIntro To Asp
Intro To Asp
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Create Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integrationCreate Home Directories on Storage Using WFA and ServiceNow integration
Create Home Directories on Storage Using WFA and ServiceNow integration
 
Object Oriented Programming with Laravel - Session 2
Object Oriented Programming with Laravel - Session 2Object Oriented Programming with Laravel - Session 2
Object Oriented Programming with Laravel - Session 2
 
mule salesforce
mule salesforcemule salesforce
mule salesforce
 
Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 

En vedette

AJAX ASP.Net
AJAX ASP.NetAJAX ASP.Net
AJAX ASP.NetSHC
 
Inside Asp.Net Web Matrix
Inside Asp.Net Web MatrixInside Asp.Net Web Matrix
Inside Asp.Net Web MatrixSHC
 
Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Arun Gupta
 
Perform brute force
Perform brute forcePerform brute force
Perform brute forceSHC
 
2011 2012 test security
2011 2012 test security2011 2012 test security
2011 2012 test securityabbutler76
 
C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)SHC
 

En vedette (7)

AJAX ASP.Net
AJAX ASP.NetAJAX ASP.Net
AJAX ASP.Net
 
Inside Asp.Net Web Matrix
Inside Asp.Net Web MatrixInside Asp.Net Web Matrix
Inside Asp.Net Web Matrix
 
Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6Boston 2011 OTN Developer Days - Java EE 6
Boston 2011 OTN Developer Days - Java EE 6
 
Minimal Change Diseas
Minimal Change DiseasMinimal Change Diseas
Minimal Change Diseas
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
2011 2012 test security
2011 2012 test security2011 2012 test security
2011 2012 test security
 
C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)C++ plus data structures, 3rd edition (2003)
C++ plus data structures, 3rd edition (2003)
 

Similaire à Rails

Similaire à Rails (20)

Ruby Rails Web Development
Ruby Rails Web DevelopmentRuby Rails Web Development
Ruby Rails Web Development
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
Building Application with Ruby On Rails Framework
Building Application with Ruby On Rails FrameworkBuilding Application with Ruby On Rails Framework
Building Application with Ruby On Rails Framework
 
Ruby on rails RAD
Ruby on rails RADRuby on rails RAD
Ruby on rails RAD
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
Ruby on rails for beginers
Ruby on rails for beginersRuby on rails for beginers
Ruby on rails for beginers
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to Rails
 
rails.html
rails.htmlrails.html
rails.html
 
rails.html
rails.htmlrails.html
rails.html
 
Ruby Rails Web Development.pdf
Ruby Rails Web Development.pdfRuby Rails Web Development.pdf
Ruby Rails Web Development.pdf
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails Basics
 
Lecture #5 Introduction to rails
Lecture #5 Introduction to railsLecture #5 Introduction to rails
Lecture #5 Introduction to rails
 
Introduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy HinyukIntroduction to Rails by Evgeniy Hinyuk
Introduction to Rails by Evgeniy Hinyuk
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 
Ruby on Rails
Ruby on Rails Ruby on Rails
Ruby on Rails
 

Plus de SHC

V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedSHC
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedSHC
 
V Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedV Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedSHC
 
Intel® V Pro™ Technology
Intel® V Pro™ TechnologyIntel® V Pro™ Technology
Intel® V Pro™ TechnologySHC
 
XForms with Linux
XForms with LinuxXForms with Linux
XForms with LinuxSHC
 
XForms
XFormsXForms
XFormsSHC
 
Call
CallCall
CallSHC
 
Action Mailer
Action MailerAction Mailer
Action MailerSHC
 
Ruby Security
Ruby SecurityRuby Security
Ruby SecuritySHC
 
Web Services
Web ServicesWeb Services
Web ServicesSHC
 
Pragmatic Agile Web Development With Rails.3rd Edition.2009
Pragmatic   Agile Web Development With Rails.3rd Edition.2009Pragmatic   Agile Web Development With Rails.3rd Edition.2009
Pragmatic Agile Web Development With Rails.3rd Edition.2009SHC
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby BasicsSHC
 
Ruby Installation
Ruby InstallationRuby Installation
Ruby InstallationSHC
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql StatmentsSHC
 
Mysql Fun
Mysql FunMysql Fun
Mysql FunSHC
 
Mysql
MysqlMysql
MysqlSHC
 
MySQL Built-In Functions
MySQL Built-In FunctionsMySQL Built-In Functions
MySQL Built-In FunctionsSHC
 
Mobile Computing
Mobile ComputingMobile Computing
Mobile ComputingSHC
 

Plus de SHC (18)

V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii EditedV Pro Bp08505 Phase Iii Edited
V Pro Bp08505 Phase Iii Edited
 
V Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii EditedV Pro Bp08505 Phase Ii Edited
V Pro Bp08505 Phase Ii Edited
 
Intel® V Pro™ Technology
Intel® V Pro™ TechnologyIntel® V Pro™ Technology
Intel® V Pro™ Technology
 
XForms with Linux
XForms with LinuxXForms with Linux
XForms with Linux
 
XForms
XFormsXForms
XForms
 
Call
CallCall
Call
 
Action Mailer
Action MailerAction Mailer
Action Mailer
 
Ruby Security
Ruby SecurityRuby Security
Ruby Security
 
Web Services
Web ServicesWeb Services
Web Services
 
Pragmatic Agile Web Development With Rails.3rd Edition.2009
Pragmatic   Agile Web Development With Rails.3rd Edition.2009Pragmatic   Agile Web Development With Rails.3rd Edition.2009
Pragmatic Agile Web Development With Rails.3rd Edition.2009
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Ruby Installation
Ruby InstallationRuby Installation
Ruby Installation
 
Mysql Statments
Mysql StatmentsMysql Statments
Mysql Statments
 
Mysql Fun
Mysql FunMysql Fun
Mysql Fun
 
Mysql
MysqlMysql
Mysql
 
MySQL Built-In Functions
MySQL Built-In FunctionsMySQL Built-In Functions
MySQL Built-In Functions
 
Mobile Computing
Mobile ComputingMobile Computing
Mobile Computing
 

Dernier

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Dernier (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

Rails

  • 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:gt; 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:ubygt; rails hello Now go into demo application root directory as follows: C:ubygt; cd hello C:ubyello> 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.
  • 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:ubyibraryonfig 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.
  • 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:ubyibrarygt; ruby script/generate model Book C:ubyibrarygt; 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.
  • 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.
  • 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