新手问题 ActiveRecord 多态关联的疑问

sec · 2016年11月23日 · 最后由 sec 回复于 2016年11月24日 · 1929 次阅读

多态关联过程中创建有虚拟 imageable 表? ①②中都可以实现功能需求,项目开发中怎么都推荐使用①,多态关联性能高效?

①使用多态关联, model里面并没有imageable,数据库里也没有imageable
class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end
===========
②没有多态关联,看起来更加简洁
class Picture < ApplicationRecord
  belongs_to :product
  belongs_to :employ
end

class Employee < ApplicationRecord
  has_many :pictures
end

class Product < ApplicationRecord
  has_many :pictures
end

第 2 中你 pictures 表需要 2 了外键字段?要是再加几个 model 还是需要 has_many :pictures,你怎么处理?

#1 楼 @nowherekai 再添加 model 的话,继续增加外键...请问是不是外键多的话,严重影响数据库效率?

def change
   add_column :pictures, :xxx_id, :integer
   add_column :pictures, :xxx_id, :integer
end

#1 楼 @nowherekai premature optimisation

多态关联过程中创建有虚拟 imageable 表?

没有创建额外的表。 guide

按照你的写法,默认会需要两个字段 imageable_idimageable_type

①②中都可以实现功能需求,项目开发中怎么都推荐使用①,多态关联性能高效?

1.你的第二种做法只是建立起了关联关系,如果你觉得这样用方便,你依然可以这么用

2.至于为什么推荐使用多态关联,你首先需要知道什么叫多态 可以屏蔽不同对象之间的差异,写出通用的代码,做出通用的编程,以适应需求的不断变化

第一种做法 从Picture的角度来看关联对象,你不需要去关注是关联了 product 还是关联了 employ

你不需要通过增加字段来适应新的关联关系

#4 楼 @angelfan 通俗易懂,谢谢

sec 关闭了讨论。 11月24日 16:26
需要 登录 后方可回复, 如果你还没有账号请 注册新账号