Single Table Inheritance (STI) column associations

五迷三道 提交于 2019-12-12 01:17:52

问题


When using single table inheritance does one have to be careful not to populate the columns which are specific to different models? Is there a way to specify which columns each model uses?


回答1:


As far as Rails is concerned, every column can be set in every subclass. You can add logic to your subclass models to prevent certain fields from being set, but there's no automated way to do so. You could probably implement it has a before_save filter.

class MySubModel < MyModel
  UNUSED_FIELDS = %w{ field_x field_y field_z } 
  def before_save
    UNUSED_FIELDS.each {|f| self.send("#{f}=", nil)}
  end
end

Although if you have a lot of columns that are only used by one subclass, STI probably isn't the best inheritance model to use.



来源:https://stackoverflow.com/questions/1160285/single-table-inheritance-sti-column-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!