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

Post on 18-Jan-2018

222 views 0 download

description

Intro

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

Introduction to information systemsRUBY 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

Intro

Convention over configuration

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

Everything may be reconfigured– but why bother?

DRY

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

somewhere, it doesn’t have to be repeated

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

Important features

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

Controllers and views

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

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

Controller

class HelloController < ApplicationController def index end def there end

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

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

View

View has access to instance attributes of invoking controller instance

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

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

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

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[]

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]

Models

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)

Active Record – typical approach

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

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,

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

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"

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']

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

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"

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)

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"

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

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

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

Active Record

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

Active Record

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

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

passwd=?", login, passwd]

Form helpers

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

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

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

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

Scaffolding

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

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

Thank you for your attentionQUESTIONS?