如何(替换|创建)rails 2.0 迁移中的枚举字段? [英] how (replace|create) an enum field on rails 2.0 migrations?

查看:15
本文介绍了如何(替换|创建)rails 2.0 迁移中的枚举字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我正在进行的迁移中创建一个枚举字段,我尝试在 google 中搜索,但在迁移中找不到方法

I would like to create an enum field at sone migration I'm doing, I tried searching in google but I can't find the way to do it in the migration

我唯一发现的是

  t.column :status, :enum, :limit => [:accepted, :cancelled, :pending]

但看起来上面的代码只在 rails 1.xxx 上运行,因为我正在运行 rails 2.0

but looks like the above code runs only on rails 1.xxx and since I'm running rails 2.0

这是我尝试过的,但失败了

this what I tried but it fails

class CreatePayments < ActiveRecord::Migration
  def self.up
    create_table :payments do |t|
      t.string :concept
      t.integer :user_id
      t.text :notes
      t.enum :status, :limit => [:accepted, :cancelled, :pending]

      t.timestamps
    end
  end

  def self.down
    drop_table :payments
  end
end

那么,如果不允许这样做,您认为什么是好的解决方案?只是一个文本字段,并通过模型进行验证?

So, in case that isn't allowed, what do you think could be a good solution? just a text field, and validating from the model?

推荐答案

您可以使用 t.column 方法手动指定类型.Rails 会将其解释为字符串列,您可以像 Pavel 建议的那样简单地将验证器添加到模型中:

You can manually specify the type by using the t.column method instead. Rails will interpret this as a string column, and you can simply add a validator to the model like Pavel suggested:

class CreatePayments < ActiveRecord::Migration
  def self.up
    create_table :payments do |t|
      t.string :concept
      t.integer :user_id
      t.text :notes
      t.column :status, "ENUM('accepted', 'cancelled', 'pending')"

      t.timestamps
    end    
  end

  def self.down
    drop_table :payments
  end
end

class Payment < ActiveRecord::Base
  validates_inclusion_of :status, :in => %w(accepted cancelled pending)
end

这篇关于如何(替换|创建)rails 2.0 迁移中的枚举字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆