代码之家  ›  专栏  ›  技术社区  ›  Coomer

不带“type”列的Rails单表继承

  •  0
  • Coomer  · 技术社区  · 16 年前

    我正在将一些功能移植到Rails,并且正在使用一个用于注释的现有表。

    基本上,有两种类型的注释-配置文件注释(photo_id列为null)和photo注释(photo_id列设置为photo的id)

    2 回复  |  直到 16 年前
        1
  •  1
  •   klew    16 年前

    如果注释模型没有太大的差异,我就不会为单表继承而烦恼了。只需添加:

    # to Comment model
    belongs_to :photo
    belongs_to :profile
    
    # to Profile model
    has_many :comments
    
    # to Photo model
    has_many :comments
    

    然后:

    @photo.comments # will return comments associated with photos
    @profile.comments # will return comments associated with profiles
    

    如果您同时设置了photo_id和profile_id,则可能会出现问题(我想在您对与profile关联的照片进行注释时可能会发生这种情况),因此您可以在profile模型中更改:

    has_many :comments, :conditions => "photo_id is not null"
    

    polymorphic associations 但是您需要修改sql表。

        2
  •  -1
  •   Michael Graff    16 年前

    我怀疑你不能做这件小事。然而,一种可能是诱使活动记录使用视图而不是表,并编写一些数据库函数来根据设置的id设置这个神奇属性。

    然而,最后,我怀疑仅仅添加列要容易得多。