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

wootaw · February 22, 2017 · Last by wootaw replied at February 23, 2017 · 1918 hits

把一个老项目中的 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
Reply to mystery

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

You need to Sign in before reply, if you don't have an account, please Sign up first.