rails开发随手记-1 多态关联 Polymorphic Associations

需求:有基类B,然后有三个子类CA,CB,CC。需要将他们关联起来。使用多态关联。

起初我想的是将CA,CB,CC 分别 belongs_to B,但这样的话B就无法显式表示与子类的关联关系。

通过多态关联.

class BaseClass< ActiveRecord::Base 
  belongs_to :childclass, :polymorphic => true 
end

class ChildClassA< ActiveRecord::Base 
  has_one :BaseClass, :as => :childclass
end 

class ChildClassB< ActiveRecord::Base 
  has_one :BaseClass, :as => :childclass
end 

class ChildClassC< ActiveRecord::Base 
  has_one :BaseClass, :as => :childclass
end 

  

class BaseClass< ActiveRecord::Migration
  def change
    create_table :BaseClass do |t|
      t.text :content
      t.integer :childclass_id
      t.string :class_type

      t.timestamps
    end
  end
end

 而对应的CA,CB,CC的Migration文件不需要改动。

这样无法保证数据层的外键关联,是因为,BaseClass中的_id关联的表是不确定的,所以无法通过外键关联。

新建对象:

c = CA.new()
b = BaseClass.new()
b. childclass = c
b.save

 b.save 之后会同时保存b和c两个对象。

感谢:http://fsjoy.blog.51cto.com/318484/96426/

  http://ihower.tw/rails3/activerecord-others.html

 

转载于:https://www.cnblogs.com/jzlikewei/archive/2013/04/13/3018611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值