TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
Rails Models
1. How to create relationships
between models
MeetUP @ Balabit
June 17, 2010
nucc@balabit.com
2. Model View Controller
http://domain/:controller/:action?p1=v1&p2=v2
router
Model Controller View
HTML, XML, JSON, CSV, ...
3. Model & Database
class Product Table products
id name
Product object
1 scb
2 syslog-ng
3 zorp
Mysql, Pgsql, Sqlite,
Model layer Oracle, Mssql
(memory) (hard disk)
4. Creating a new row
1.
product = Product.new class Product
Table products
id name
2.
1 scb
product.name = “ssb”
2 syslog-ng
3. 3 zorp
product.save! / product.save validation 4 ssb
4. ...
error
Model Database
(memory) (disk)
5. Validating
class Product
validates_presence_of :name
validate :my_validator
def my_validator
if name.length < 3
errors.add :name, “is too short”
end
end
end
11. Relations
Product Owner
scb marci
ssb
class Product class Owner
belongs_to :product_owner has_many :products
end end
products owner
id name owner_id id name
1 scb 1 1 marci
2 ssb 1
12. Has and belongs to many
Developer Product
tia scb
gyp ssb
class Developer class Product
has_and_belongs_to_many :products has_one :owner
end has_and_belongs_to_many :developers
end
developers developers_products products
id name developer_id product_id id name owner_id
1 gyp 1 1 1 scb 1
2 tia 1 2 2 ssb 1