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

 

posted @ 2013-04-13 16:27  jzlikewei  阅读(271)  评论(0编辑  收藏  举报