+ All Categories
Home > Documents > Download It

Download It

Date post: 19-May-2015
Category:
Upload: sampetruda
View: 677 times
Download: 0 times
Share this document with a friend
Popular Tags:
41
CM0133 Ruby On Rails Ruby On Rails and More
Transcript
Page 1: Download It

CM0133 Ruby On Rails

Ruby On Rails and MoreRuby On Rails and More

Page 2: Download It

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

Page 3: Download It

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

Page 4: Download It

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

Page 5: Download It

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

Page 6: Download It

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?

Page 7: Download It

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

Page 8: Download It

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

Page 9: Download It

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

Page 10: Download It

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!

Page 11: Download It

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

Page 12: Download It

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

Page 13: Download It

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’

Page 14: Download It

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

Page 15: Download It

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)

Page 16: Download It

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)

Page 17: Download It

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)

Page 18: Download It

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

Page 19: Download It

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

Page 20: Download It

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

Page 21: Download It

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

Page 22: Download It

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

Page 23: Download It

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

Page 24: Download It

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

Page 25: Download It

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)

Page 26: Download It

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

Page 27: Download It

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

Page 28: Download It

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)

Page 29: Download It

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

Page 30: Download It

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

Page 31: Download It

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’

Page 32: Download It

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

Page 33: Download It

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

Page 34: Download It

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

Page 35: Download It

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

Page 37: Download It

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 %>

Page 38: Download It

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?

Page 39: Download It

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

Page 40: Download It

CM0133 Ruby On Rails

Some More Ajax ExamplesSome More Ajax Examples

• http://www.writely.com/

• http://instantdomainsearch.com/

• http://www.netflix.com/Top100

Page 41: Download It

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


Recommended