Download It
Upcoming SlideShare
Loading in...5
×
 

Download It

on

  • 730 views

 

Statistics

Views

Total Views
730
Views on SlideShare
730
Embed Views
0

Actions

Likes
0
Downloads
2
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Download It Download It Presentation Transcript

  • Ruby On Rails and More
  • Previously
    • Saw the MVC methodology
    • Used scaffold to create a simple application
    • CreateReadUpdateDelete (CRUD)
    • All working on a single MySQL table
  • Rails Active Records
    • This is the Object Relational Mapping layer
    • Allows mapping between the application and the database
    • Relies on the naming convention
    View slide
  • Rails 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
    View slide
  • Active 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
  • Multiple 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?
  • Model 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
  • Declaring your associations
    • Add the declarations to your model files
    • So car.rb should look like
    class Car < ActiveRecord::Base belongs_to :manufacturer end Inherits
  • Declaring your associations
    • Likewise the manufacturer.rb file should look like
    class Manufacturer < ActiveRecord::Base has_many :cars end Note the plural
  • Validating 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!
  • Validation 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
  • More 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
  • 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’
  • Migration
    • 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
  • Migration 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)
  • Migration 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)
  • Database column options
    • Valid column options are:
    • limit ( :limit => “50” )
    • default (:default => “b l ah”)
    • null (:null => false implies NOT NULL)
    • Source (tutorialspoint.com)
  • Generating 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
  • The 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 end end Migrate the database forward Rollback
  • Using 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
  • Using 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
  • Retrieving 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
  • Creating 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
  • Saving data
    • If we have an object that has been populated saving is easy!!
    • We can send this data to the database…
    • @car.save
  • Where 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)
  • Removing data
    • As you have seen database manipulation is quite straight forward
    • Deleting an entry is no different
    • Car.find(params[:id]).destroy
  • How 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&quot;> <% @cars.each do |c| %> <li> <%= link_to c.model, {:action => 'show', :id => c.id} -%> </li> <% end %> </ul> <% end %> <p> <%= link_to &quot;Add new Car&quot;, {:action => 'new' }%> </p> Any entries? For each car found create a hyper link and put it as a list item
  • link_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)
  • link_to examples link_to &quot;Visit Other Site&quot;, &quot;http://www.rubyonrails.org/&quot;, :confirm => &quot;Are you sure?&quot; # => <a href=&quot;http://www.rubyonrails.org/&quot; onclick=&quot;return confirm('Are you sure?');&quot;>Visit Other Site</a> link_to &quot;Help&quot;, { :action => &quot;help&quot; }, :popup => true # => <a href=&quot;/testing/help/&quot; onclick=&quot;window.open(this.href);return false;&quot;>Help</a> link_to &quot;View Image&quot;, { :action => &quot;view&quot; }, :popup => ['new_window_name', 'height=300,width=600'] # => <a href=&quot;/testing/view/&quot; onclick=&quot;window.open(this.href,'new_window_name','height=300,width=600');return false;&quot;>View Image</a> Source rubyonrails.com
  • Making 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
  • Yield
    • 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’
  • Ajax
    • 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
  • Web 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
  • Data 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
  • 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
  • Some 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
  • Ajax 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 %>
  • Updating 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?
  • 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
  • Some More Ajax Examples
    • http://www.writely.com/
    • http://instantdomainsearch.com/
    • http://www.netflix.com/Top100
  • More 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