ruby里的表對應的三關系:
在mysql里創建兩張表
mysql> create table invoices(
??? -> id int primary key auto_increment,
??? -> order_id int,
??? -> created_at timestamp
??? -> );
Query OK, 0 rows affected (0.28 sec)
mysql> create table orders(
??? -> id int primary key auto_increment,
??? -> company varchar(30)
??? -> );
Query OK, 0 rows affected (0.23 sec)
(1)one to one relationShip:
?? order.rb
?? class Order < ActiveRecord::Base
?? has_one:invoice
?? end
?? invoice.rb
?? class Invoice < ActiveRecord::Base
??? belongs_to:order
?? end
?? D:\ruby\mytest\mytest1>ruby script\console
?? Loading development environment.
?? >> order=Order.new
?? => #<Order:0x4872e78 @new_record=true, @attributes={"company"=>nil}>
?? >> order.company="Big Corp"
?? => "Big Corp"
?? >> order.save
?? => true
?? >> invoice=Invoice.new
?? => #<Invoice:0x485c5ec @new_record=true, @attributes={"order_id"=>nil, "created_
?? at"=>nil}>
?? >> order.invoice=invoice
?? => #<Invoice:0x485c5ec @errors=#<ActiveRecord::Errors:0x4858730 @errors={}, @bas
?? e=#<Invoice:0x485c5ec ...>>, @new_record=false, @attributes={"order_id"=>1, "id"
?? =>1, "created_at"=>Sat Mar 31 14:41:32 +0800 2007}>
?? >>
(2)one to many
? mysql> create table comments
??? -> (
??? -> id int primary key auto_increment,
??? -> comment varchar(5000),
??? -> created_at timestamp,
??? -> updated_at timestamp
??? -> );
Query OK, 0 rows affected (0.31 sec)
mysql> alter table comments add critic_id int;
Query OK, 0 rows affected (0.42 sec)
Records: 0? Duplicates: 0? Warnings: 0
mysql> create table critics
??? -> (
??? -> id? int primary key auto_increment,
??? -> firstname varchar(30),
??? -> lastname varchar(30),
??? -> email varchar(30)
??? -> );
Query OK, 0 rows affected (0.11 sec)
class Critic < ActiveRecord::Base
? has_many:comment
end
class Comment < ActiveRecord::Base
? belongs_to:critic
end
D:\ruby\mytest\mytest1>ruby script\console
Loading development environment.
>> a_critic=Critic.new
=> #<Critic:0x486ffd4 @new_record=true, @attributes={"lastname"=>nil, "firstname
"=>nil, "email"=>nil}>
>> a_critic.lastname="adm"
=> "adm"
>> a_critic.save
=> true
>> a_comment=Comment.new
=> #<Comment:0x485a1fc @new_record=true, @attributes={"updated_at"=>nil, "critic
_id"=>nil, "comment"=>nil, "created_at"=>nil}>
>> a_comment.comment="this is a movie"
=> "this is a movie"
>> a_critic.comment<<a_comment
(3)many to many
?? 有三張表table1s ,table1s_table2s,table2s
?? 分別在table1.rb,table2.rb增加下面的語句
?? has_and_belongs_to_many:table1;
?? has_and_belongs_to_many:table2
操作與(2)相似