download it
TRANSCRIPT
CM0133 Ruby On Rails
Ruby On Rails and MoreRuby On Rails and More
CM0133 Ruby On Rails
PreviouslyPreviously
• Saw the MVC methodology
• Used scaffold to create a simple application
• CreateReadUpdateDelete (CRUD)
• All working on a single MySQL table
CM0133 Ruby On Rails
Rails Active RecordsRails Active Records
• This is the Object Relational Mapping layer
• Allows mapping between the application and the database
• Relies on the naming convention
CM0133 Ruby On Rails
Rails friendly MySQLRails friendly MySQL
• The naming convention carries into the database design
• Each entity in our domain has a table in the database.
• Naming convention gives car (entity) maps to cars (table)
• Each table has a unique number field which is called id
• If the entity car belongs_to manufacturer then there will be a manufacturer_id in the cars table
CM0133 Ruby On Rails
Active Record FilesActive Record Files
• We have looked at these before
• These belong to the model part of the MVC
• We created these using the generator script
• script/generate model Car
CM0133 Ruby On Rails
Multiple Tables/ModelsMultiple Tables/Models
• So far we have looked at applications with a single table/model
• What if we have many tables/models
• How do we incorporate relationships between these tables/models?
CM0133 Ruby On Rails
Model AssociationsModel Associations
• one-to-one– A car has one steering wheel
• one-to-many– A manufacturer has many cars
• many-to-many– A manufacturer has many points of sale– Each point of sale has many manufactures
CM0133 Ruby On Rails
Declaring your associationsDeclaring your associations
• Add the declarations to your model files
• So car.rb should look like
class Car < ActiveRecord::Base
belongs_to :manufacturer
end
Inherits
CM0133 Ruby On Rails
Declaring your associationsDeclaring your associations
• Likewise the manufacturer.rb file should look like
class Manufacturer < ActiveRecord::Base
has_many :cars
end Note the plural
CM0133 Ruby On Rails
Validating DataValidating Data
• You can place your validations inside your models as well
• This is used to ensure the correct data is entered into the database
• Users can make mistakes!
CM0133 Ruby On Rails
Validation MethodsValidation Methods
• validates_presence_of:– Has the field been filled in
• validates_length_of:– How many characters are there
• validates_acceptance_of:– You can set what the user should enter I.e. a
confirming they have read and ticked something• validates_confirmation_of:
– For passwords
CM0133 Ruby On Rails
More Validation MethodsMore Validation Methods
• validates_uniqueness_of:– Makes sure an entry is unique
• validates_format_of:– For things like email etc
• validates_numericality_of:– Is a field numberic
• validates_inclusion_of:– Can check for inclusion in a range
CM0133 Ruby On Rails
Even More Validation Methods
Even More Validation Methods
• validates_exclusion_of:– Is not within some range
• To output an error message on failure to validate– :message => ‘This failed to validate’
CM0133 Ruby On Rails
MigrationMigration
• Allows for easy database control
• Updates to the database are easy
• Multiple people/machines can update from a migration file
• Migration allows you to perform many operations on your database
CM0133 Ruby On Rails
Migration methodsMigration methods
• create_table(name, options)• drop_table(name)• rename_table(old_name, new_name)• add_column(table_name, column_name, type, options)• rename_column(table_name, column_name,
new_column_name)• change_column(table_name, column_name, type, options)• remove_column(table_name, column_name)• add_index(table_name, column_name, index_type)• remove_index(table_name, column_name)Source (tutorialspoint.com)
CM0133 Ruby On Rails
Migration data typesMigration data types
• string - is for small data types such as a title.• text - is for longer pieces of textual data, such as the
description.• integer - is for whole numbers.• float - is for decimals.• datetime and timestamp - store the date and time into a
column.• date and time - store either the date only or time only.• binary - is for storing data such as images, audio, or movies.• boolean - is for storing true or false values.Source (tutorialspoint.com)
CM0133 Ruby On Rails
Database column optionsDatabase column options
• Valid column options are:
• limit ( :limit => “50” )
• default (:default => “blah”)
• null (:null => false implies NOT NULL)Source (tutorialspoint.com)
CM0133 Ruby On Rails
Generating migrationsGenerating migrations
• Migrations can be created using the generate script
• script/generate migration cars
• This creates the migration for the table cars which is the plural of the entity car
CM0133 Ruby On Rails
The migration fileThe migration file
class Cars < ActiveRecord::Migration def self.up create_table :cars do |t| t.column :model, :string, :limit => 32, :null => false t.column :price, :float t.column :colour, :string t.column :created_at, :timestamp end end def self.down drop_table :cars endend
Migrate the database forward
Rollback
CM0133 Ruby On Rails
Using the migration fileUsing the migration file
• As mentioned before we use the rake utility to migrate the database
• This acts as a Version Control System
• This tracks all the changes we make to the database using rake
• rake db:migrate
CM0133 Ruby On Rails
Using the controllersUsing the controllers
• We have seen that controllers are the ‘go-between’ of the application
• They link the front end to the database
• Sending and receiving data from the database
CM0133 Ruby On Rails
Retrieving dataRetrieving data
• @cars = Car.find(:all)– Retrieve all the entries in the cars table
• @car = Car.find(params[:id])– Retrieve the entry in the database with the
params id. Id is usually dependant on the user clicking on a db entry in the front end. Params lets you pass information
CM0133 Ruby On Rails
Creating objectsCreating objects
• ‘new’ is used to create a new object• @car = Car.new(params[:car])• Again params is used to pass data
which we have probably received from the user Interface
CM0133 Ruby On Rails
Saving dataSaving data
• If we have an object that has been populated saving is easy!!
• We can send this data to the database…
• @car.save
CM0133 Ruby On Rails
Where to send the userWhere to send the user
• We can send the user to different places dependant on some output
• E.g. if some code fails send them to a else send them to b
• redirect_to :action => ’show’– Takes them back to the show method and renders
that template (view file)
• render :action => ‘list’– Render the ‘list’ template (view file)
CM0133 Ruby On Rails
Removing dataRemoving data
• As you have seen database manipulation is quite straight forward
• Deleting an entry is no different• Car.find(params[:id]).destroy
CM0133 Ruby On Rails
How the view code looksHow the view code looks<% if @cars.blank? %> <p> There are not any cars in the database yet </p><% else %> <p> The cars we have found in the database are… </p> <ul id=”cars"> <% @cars.each do |c| %> <li> <%= link_to c.model, {:action => 'show', :id => c.id} -%> </li> <% end %> </ul><% end %><p> <%= link_to "Add new Car", {:action => 'new' }%></p>
Any entries?
For each car found create a hyper link and put it as a list item
CM0133 Ruby On Rails
link_to methodlink_to method
• In the last slide we used the link_to method
• Dynamicaly make links that depend on the routing system (defind in routes.rb)
• link_to(name, options = {}, html_options = nil)
CM0133 Ruby On Rails
link_to exampleslink_to examples
link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
# => <a href="http://www.rubyonrails.org/" onclick="return confirm('Are you sure?');">Visit Other Site</a>
link_to "Help", { :action => "help" }, :popup => true
# => <a href="/testing/help/" onclick="window.open(this.href);return false;">Help</a>
link_to "View Image", { :action => "view" }, :popup => ['new_window_name', 'height=300,width=600']
# => <a href="/testing/view/" onclick="window.open(this.href,'new_window_name','height=300,width=600');return false;">View Image</a>
Source rubyonrails.com
CM0133 Ruby On Rails
Making it look niceMaking it look nice
• We can define layouts for our applications• Then apply that layout to any page• They live in app/views/layouts• Similar to dreamweaver et al• Create your layout_file.rhtml• Add your HTML• Add a style sheet
CM0133 Ruby On Rails
YieldYield
• You must place a ruby command in the layout file so Rails knows where to add data
• <%= yield -%>• In the controller file you wish to apply
this layout to…. Add• layout ’layout_file’
CM0133 Ruby On Rails
AjaxAjax
• Asyncronous JavaScript and XML
• Ajax has had a massive impact on application design
• Previously the web was a poor place for many applications
• Ajax has changed much of this, especially when linked in with RoR etc
CM0133 Ruby On Rails
Web applicationsWeb applications
• Previously web applications were very limited
• They were not very interactive
• Sending and receiving data was slow and clunky
• Showing changing data was difficult
CM0133 Ruby On Rails
Data ExchangeData Exchange
• Ajax allows for data to be sent and received without the whole page updating
• This makes for a more fluid experience• Increases interactivity• Increases speed• Less data is sent/received• Makes the page more usable
CM0133 Ruby On Rails
How does it work?How does it work?
• It uses Javascript to make the function calls that get/send data
• Data is retrieved from the server using the XMLHttpRequest technology
• This is what makes it possible to exchange data with the server without the need for full page reloads
CM0133 Ruby On Rails
Some Ajax example sitesSome Ajax example sites
• http://maps.google.com/• http://www.google.com/webhp?complete=1&hl=en
• http://maps.yahoo.com/• http://www.tutorialspoint.
com/cgi-bin/ajaxCGI.cgi?num1=1&num2=1&result=0&semajax=Standard
CM0133 Ruby On Rails
Ajax and RailsAjax and Rails
• Luckily Rails has incorporated Ajax so that we can make interactive pages
• We can include the necessary files in our layout page to save doing this over and over
• <%= javascript_include_tag :defaults %>
CM0133 Ruby On Rails
Updating with AjaxUpdating with Ajax
<%= form_remote_tag(
:url => {:action => 'create'},
:update => “manufacturer_list”,
:position => :bottom,
:html => {:id => ‘manufacturer_form’}
)%>
Create a form
When we press the button
Whats updated?
Top or bottom of the list?
CM0133 Ruby On Rails
What does this do?What does this do?
• It will submit to ‘create’ th string given by the form
• It will update the manufacturers list which has been given an id tag
• We make sure the new item goes at the bottom of the list
CM0133 Ruby On Rails
Some More Ajax ExamplesSome More Ajax Examples
• http://www.writely.com/
• http://instantdomainsearch.com/
• http://www.netflix.com/Top100
CM0133 Ruby On Rails
More RailsMore Rails
• RoR also allows you to quickly generate other tools for your web application
• Uploading and downloading of files can also be achieved int RoR
• Email tools, so you can be contacted from a web form easily
• Use http://api.rubyonrails.org/ for a reference site