Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

43
Introductio n to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz

description

Intro

Transcript of Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Page 1: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Introduction to information systemsRUBY ON RAILS

dr inż. Tomasz Pieciukiewicz

Page 2: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Rails–web development framework for Ruby

Introduction to Rails View and Controller in Rails Model in Rails Scaffolding Plugins

Page 3: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Intro

Page 4: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Convention over configuration

Use of default settings, configuration and coding standards results in shorter ,easier code

Everything may be reconfigured– but why bother?

Page 5: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

DRY

Don’t repeat yourself If a programmer stated a piece of information

somewhere, it doesn’t have to be repeated

Page 6: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Command line

Important operations are executed with command line - invoked scripts, e.g.: rails new appName – generate app skeleton rails server – run built-in www server rails generate controller Name –create controller

class Gem –command line tool for package

downloads (apt equivalent) Rake – Ant equivalent

Page 7: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Important features

MVC based built in ORM many utility packages seriously reduces development time

Page 8: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Controllers and views

Page 9: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Controller

Controller class extends the Application Controller class

Class name is NameController Class is saved to name_controller.rb in the

controllers folder controllers folder may contain subfolders ->

controller hierarchy

Page 10: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Controller

With default routing rules each method in the controller is an action URL contains method's name

http://whatever.com/myApp/myController/action parameters may be passed this way: http://whatever.com/myApp/myController/

action/param1/param2

Page 11: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Controller

class HelloController < ApplicationController def index end def there end

Page 12: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View

View is a .erb.html file with the same name, as the action using it, put in the application folder , views\controller Name subfolder

.erb.html is html with embedded Ruby code

Page 13: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View

Ruby code is put in <% %> tags Expression values are in<%= %> tags Like in other similar languages, Ruby codemay

be used to display HTML in certainways(loops, conditional expressions)

Code should be limited to view-related processing, business logic goes into controller

and/or model

Page 14: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View

View has access to instance attributes of invoking controller instance

This way , we may easily pass information from controller to view

Page 15: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View

By default, the controller's action renders the appropriate view at the end of its execution

render method may be used to display a different view: render(:action => :actionName) –displays view

related to a specific action render(:file => path) –displays view from a

specific file

Page 16: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View

hrefs to to other actions may be inserted using link_to method

<%= link_to"text", :action=>"actionname"%> <%=

link_to"text", :controller=>"controllername", :action=>"actionname%>

Page 17: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View and controller

Access to request parameters –using the params array:params[:paramName] If a form element (e.g. select) may return

multiple values, its name has to end with[]

Page 18: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

View and controller

Session variables are stored in session association array:

session[:data]=@data @data=session[:data] Access to cookies using cookies association

array: cookies[:name]={:value=>value, :expires=whe

n} @data=cookies[:name]

Page 19: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Models

Page 20: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Custom implementation

Located in the models folder Each model class defines its own methodsand

attributes, handles persistence May extend e.g. the Base class (class that

implements database access)

Page 21: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record – typical approach

Create tables in database Configure the database.yml file (config folder) Generate model rails generate model modelName

Page 22: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Database tables

Convention over configuration Names in plural (english rules), e.g.: Table bikes -> class Bike Table people -> class Person Primary key should be named id and be

integer . Autoincrement is a good idea here ;) Foreign keys – name of the foreign table in

singular+"_id", eg person_id, bike_id,

Page 23: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record classes

Simple Active Record class: class Purchase < ActiveRecord::Base end This class provides access to all tuple's columns

(read and write), searching etc. We have to define relations with other tables

and operations

Page 24: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Record creation Using new method to create object and save to

save it to DB: b = Book.new :title=>"sth", :author=>"auth" b.save Using create method (w/o save): Book.create :title=>"sth",:author=>"auth"

Page 25: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Record deletion Database-level

delete(id) delete 552 delete_all [condition] Book.delete_all (['year<?',2007])

Object-level (recommended) - destroy @CurrentBook.destroy destroy_all [condition] destroy_all ['alive=0']

Page 26: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Updates save – saves all changes to the database CurrentBook.save update_attribute – updates a specified attribute CurrentBook.update_attribute :title=>'RoR' update_attributes – updates a specified set of attributes CurrentBook.update_attributes {:title=>'RoR', :year=>2007} update_all – update to a large group of records, change

and conditions have to be specified Book.update_all "price=1.22*price", :year=>2008

Page 27: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Searching within model, using SQL find_by_sql "sql query" User.find_by_sql "SELECT * FROM users" count_by_sql "sql query" User.count_by_sql "SELECT COUNT(*) FROM users"

Page 28: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Searching outside model, using SQL connection.select_all "sql query" connection.select_one "sql query" connection.execute "sql query" (does not have

to be search)

Page 29: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Searching using Active Record methods Model.find id – using primary key as parameter Book.find 548 Model.find :conditions=>['column=?',value] Book.find :conditions => ['id=?',2] Book.find :conditions => {:id=>2} Model.find_by_xxx and Model.find_all_by_xxx – created automatically for all columns, xxx is the name of the column Book.find_by_id 222 Book.find_by_id [1,345,1112] Book.find_all_by_title "Bible"

Page 30: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Relationships belongs_to – n-side of 1:n relationship (n=1 or *) has_one – 1-side of 1:1 relationship has_many – 1-side of 1:* relationship has_and_belongs_to_many – relationship *:*, a table named table1_table2 must exist – will be

used to estabilish *:* relationship

Page 31: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Basic data validation validates_presence_of :column - check if column contains data guess: validates_acceptance_of validates_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of

Page 32: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

Data validation using methods: class Comment < ActiveRecord::Base validate :must_be_friends def must_be_friends errors.add_to_base("Must be friends \ to leave a comment") unless \ commenter.friend_of?(commentee) end end

Page 33: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

classBook < ActiveRecord::Base has_and_belongs_to_many: authors has_many:editions validates_presence_of :title, :price end

Page 34: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Active Record

SQL Injection protection Never: User.all :conditions => "login='#{login}' AND

passwd='#{passwd}'" Always: User.all :conditions => ["login=? AND

passwd=?", login, passwd]

Page 35: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Form helpers

Page 36: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

form_for

form_for - used for HTML forms based upon ActiveRecord objects

<%= form_for(:class, @instanceAttribute , :url => { :controller => "controller", :action =>

"action" }, :html => { :multipart => true, :method

=> :put }) do |f| %> ... <% end %>

Page 37: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

form_for

:class - (required) name of model object for fields. Input fields will be prefixed with this

@instanceAttribute - (optional) ActiveRecord model object, if named differently than class

:html - (optional) hash of HTML attributes for <form> tag

:method - (optional) HTTP method to use :url - url to post the form to |f| - form object, used to create fields

Page 38: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Input field helpers

Multiple helpers, each used to create different type of form field f.error_messages_for f.check_box f.file_field f.hidden_field f.label f.password_field f.radio_button f.text_area f.text_field Description of parameters can be found here: http://rails.rubyonrails.org/classes/ActionView/Helpers/

FormHelper.html

Page 39: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

More helpers

There are also helpers used to create select fields from collections:

http://rails.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html create date and time input fields

http://rails.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html and many others

Page 40: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Scaffolding

Page 41: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Scaffolding

Scaffolding allows us to quickly and easily create a simple CRUD application

It also generates Ruby code required to create a database following a certain specification

The DB schema may be migrated to a DB server by using the Rake tool

Page 42: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Scaffolding

Creating scaffolding: rails generate scaffold ModelName

column:type, column:type … rails generate scaffold Movie title:string

description:text one_sheet_url:string Migrating database rake db:migrate

Page 43: Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz.

Thank you for your attentionQUESTIONS?