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

查看:67
本文介绍了如何(替换|创建)在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天全站免登陆