how (replace|create) an enum field on rails 2.0 migrations?

后端 未结 10 1600
轮回少年
轮回少年 2020-12-07 10:27

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

the only thing I f

相关标签:
10条回答
  • 2020-12-07 10:52

    Add the following:

    module ActiveRecord
      module ConnectionAdapters #:nodoc:
        class TableDefinition
          def enum(*args)
            options = args.extract_options!
            column_names = args
    
            column_names.each { |name| column(name, 'enum', options) }
          end
        end
      end
    end
    

    to lib/enum/table_definition.rb and include it in your init.rb.

    0 讨论(0)
  • 2020-12-07 10:58

    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
    
    0 讨论(0)
  • 2020-12-07 10:58

    Similarly, the enumerated_attribute gem manages enums at the object level.

    enum_attr :status, %w(accepted cancelled ^pending)
    

    Define a string in the migration

    t.string :status 
    

    Also provides some nice features like dynamic predicate methods.

    http://github.com/jeffp/enumerated_attribute/tree/master

    0 讨论(0)
  • 2020-12-07 11:01

    ok, just read the whole rails api and found what I neeed and I dont like :( Rails doesn't support emum as native type on migrations, here is the info, I need to search for a plugin or other method.

    I will keep you posted.

    0 讨论(0)
提交回复
热议问题