探索与发现

研究java技术

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  83 随笔 :: 0 文章 :: 109 评论 :: 0 Trackbacks
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)相似
posted on 2007-03-31 16:08 蜘蛛 阅读(462) 评论(0)  编辑  收藏 所属分类: ruby

只有注册用户登录后才能发表评论。


网站导航: