Rails 在项目中使用 AASM enum 全面替换 state_machines 的 migration

wootaw · 2017年02月22日 · 最后由 wootaw 回复于 2017年02月23日 · 1915 次阅读

把一个老项目中的 state_machines 全部替换掉,使用 AASM enum,因为字段类型变了,字段名称不想变(强迫症犯了)。

class ReplaceStateMachines < ActiveRecord::Migration
  def change

    [Order, Customer].each do |clazz|
      ActiveRecord::Base.connection.execute("select * from #{clazz.table_name}").each do |r|
        ActiveRecord::Base.connection.execute("update #{clazz.table_name} set state = #{clazz.states[r["state"]]} where id = #{r["id"]}")
      end
      ActiveRecord::Base.connection.execute("ALTER TABLE #{clazz.table_name} ALTER COLUMN state TYPE integer USING (trim(state)::integer)")
    end

  end
end

是否可以精简一下,没验证!

[Order, Customer].each do |clazz|
  clazz.all.each{|record| record.where(state: clazz.states[record["state"]]) }
  ActiveRecord::Base.connection.execute("ALTER TABLE #{clazz.table_name} ALTER COLUMN state TYPE integer USING (trim(state)::integer)")
end
mystery 回复

不可以啊,因为在 model 里我已经把 AASM 的代码完全替换了 state_machines,这个时候再用 ActiveRecord 里的方法(.all, .where)会得到错误的数据(因为数据库里的字段类型不同了)。这个 migration 跑完后,ActiveRecord 里的方法就恢复正常了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号