Download presentation
Presentation is loading. Please wait.
Published byMarylou Simon Modified over 9 years ago
1
Introduction to information systems RUBY ON RAILS dr inż. Tomasz Pieciukiewicz
2
Rails–web development framework for Ruby Introduction to Rails View and Controller in Rails Model in Rails Scaffolding Plugins
3
Intro
4
Convention over configuration Use of default settings, configuration and coding standards results in shorter,easier code Everything may be reconfigured– but why bother?
5
DRY Don’t repeat yourself If a programmer stated a piece of information somewhere, it doesn’t have to be repeated
6
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
7
Important features MVC based built in ORM many utility packages seriously reduces development time
8
Controllers and views
9
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
10
Controller With default routing rules each method in the controller is an action URL contains method's name http://whatever.com/myApp/myController/actio n parameters may be passed this way: http://whatever.com/myApp/myController/actio n/param1/param2
11
Controller class HelloController < ApplicationController def index end def there end
12
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
13
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
14
View View has access to instance attributes of invoking controller instance This way, we may easily pass information from controller to view
15
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
16
View hrefs to to other actions may be inserted using link_to method "actionname"%> "controllername", :action=>"actionname%>
17
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[]
18
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=when} @data=cookies[:name]
19
Models
20
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)
21
Active Record – typical approach Create tables in database Configure the database.yml file (config folder) Generate model rails generate model modelName
22
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,
23
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
24
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"
25
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']
26
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
27
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"
28
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)
29
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"
30
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
31
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
32
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
33
Active Record classBook < ActiveRecord::Base has_and_belongs_to_many: authors has_many:editions validates_presence_of :title, :price end
34
Active Record SQL Injection protection Never: User.all :conditions => "login='#{login}' AND passwd='#{passwd}'" Always: User.all :conditions => ["login=? AND passwd=?", login, passwd]
35
Form helpers
36
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| %> ...
37
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 tag :method - (optional) HTTP method to use :url - url to post the form to |f| - form object, used to create fields
38
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
39
More helpers There are also helpers used to create select fields from collections: http://rails.rubyonrails.org/classes/ActionView/Hel pers/FormOptionsHelper.html create date and time input fields http://rails.rubyonrails.org/classes/ActionView/Hel pers/DateHelper.html and many others
40
Scaffolding
41
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
42
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
43
Thank you for your attention QUESTIONS?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.