【发布时间】:2016-10-08 16:24:15
【问题描述】:
我正在更改现有应用程序中使用 STI 扩展的基本模型的 inheritance_column 值。如何编写迁移以使现有列符合新的inheritance_column?
这是我的第一次尝试:
class MigrateStoryTypes < ActiveRecord::Migration
def self.up
Story.all.each { |story|
new_story_type = story.story_type.camelize + 'Story'
puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}"
story.update_column :story_type, new_story_type
}
end
def self.down
Story.all.each { |story|
new_story_type = story.story_type.underscore.gsub /_story/, ''
puts "changing #{story.id}'s story_type from #{story.story_type} to #{new_story_type}"
story.update_column :story_type, new_story_type
}
end
end
但是,这失败了:
ActiveRecord::SubclassNotFound:单表继承机制 未能找到子类:'clean_slate'。引发此错误 因为“story_type”列是为存储类而保留的 继承的情况。如果您不打算这样做,请重命名此列 用于存储继承类或覆盖 Story.inheritance_column 为该信息使用另一列。
是否有通过 ActiveRecord 直接执行此操作的方法,或者我是否需要使用临时列、SQL 等?
【问题讨论】:
-
所以你已经有一个
story_type列,其中包含类名的下划线版本(即'clean_slate'),现在你想将它移动到 STI,使用story_type作为 STI 列,并将story_type值转换为类名?你目前有多少个story_type值? -
@muistooshort 没错。我目前有两个
story_type值。
标签: ruby-on-rails postgresql rails-activerecord