24. CREATE TABLE orders (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
An
order_date TIMESTAMP NOT NULL,
price_total DOUBLE NOT NULL
);
example
CREATE TABLE products (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
from a
name VARCHAR(80) NOT NULL,
price DOUBLE NOT NULL
);
Hibernate
CREATE TABLE order_items (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
tutorial
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
amount INTEGER NOT NULL,
price DOUBLE NOT NULL
);
25. public class Order
Java
{
private Integer id;
private Date date;
private double priceTotal;
Object
private Set orderItems = new HashSet();
public Order() {
Model:
this.date = new Date();
}
public Integer getId() {
Order
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(date) {
this.date = date;
}
public void addProduct(Product p, int amount) {
OrderItem orderItem = new OrderItem(this, p, amount);
this.priceTotal = this.priceTotal + p.getPrice() * amount;
this.orderItems.add(orderItem);
}
}
27. Rails Data Model:
Order
class Order < ActiveRecord::Base
has_many :order_items
def add_product(product, amount)
order_item = OrderItem.new(product, amount)
self.price_total += product.price * amount
order_items << order_item
end
end
31. Dispatch based on URLs
http://myapp/orders/show/1
Application
controller
action
id
*customizable by Routing
32. Action grouped in Controller
class OrdersController < ApplicationController
def index
list
# Default to app/views/orders/index.rhtml
render :action => 'list'
end
def list
@order_pages, @orders =
paginate :orders, :per_page => 10
end
def show
@order = Order.find(params[:id])
end
end
33. Rendering and Redirection
def update
@order = Order.find(params[:id])
if @order.update_attributes(params[:order])
flash[:notice] =
'Order was successfully updated.'
redirect_to :action => 'show', :id => @order
else
render :action => 'edit'
end
end
35. Associations
class Order < ActiveRecord::Base
has_many :order_items
end
the_order = Order.find :first
the_oder.oder_items.each do |item|
print item.name
end
* Some other associations: has_one,
belongs_to, has_and_belongs_to_many...
36. Validations
class Product < ActiveRecord::Base
validates_presenc_of :name
validtaes_numericality :price
end
Hooks
class Order < ActiveRecord::Base
def before_destory
order_items.destory_all
end
end
39. Rails makes it fast to
develop, but the true
power behind Rails is
RUBY
40. Blocks
• Iteration
5.times { |i| puts i }
[1,2,3].each { |i| puts i }
• Resource Management
File.open(’t.txt’) do |f|
#do something
end
• Callback
TkButton.new do
text “EXIT”
command { exit}
end
41. New Language Construct
Rakefile
task :test => [:compile, :dataLoad] do
# run the tests
end
Markaby
html do
body do
h1 ‘Hello World’
end
end
43. Meta - Programming
class Order < ActiveRecord::Base
has_many :order_items
end
class Product < ActiveRecord::Base
validates_presenc_of :name
validtaes_numericality :price
end