How do I describe an enumeration column in a Rails 3 migration?

前端 未结 11 1460
误落风尘
误落风尘 2020-12-24 04:23

How do I describe an enumeration column in a Rails 3 migration?

相关标签:
11条回答
  • 2020-12-24 05:25

    In a Rails 3 Migration you can do the following:

    class CreateFoo < ActiveRecord::Migration
      def change
        create_table :foo do |t|
          t.column :foobar, "ENUM('foo', 'bar')"
        end
      end
    end
    

    This will create the table with the single column "foobar" and the values.

    0 讨论(0)
  • 2020-12-24 05:25

    You can describe an enumeration column with:

    t.column 'role', 'user_role'
    

    I created the enum type with:

    execute "CREATE TYPE user_role AS ENUM ('consultant', 'admin');"
    

    Inspecting the database:

        Column     |          Type          | Modifiers | Storage  | Stats target | Description
    ---------------+------------------------+-----------+----------+--------------+-------------
     role          | user_role              |           | plain    |              |
    
    0 讨论(0)
  • 2020-12-24 05:27

    What worked for me was mapping it from symbols to integers

    TYPE_MAP = { type_one: 1, type_two:2, another_type:3 }
    
    def type
        TYPE_MAP.key(read_attribute(:type))
    end
    
    def type=(s)
        write_attribute(:type, TYPE_MAP[s])
    end
    

    But for the controller you have to map it again like this:

     def create
      @cupon_type = CuponType.new(params[:cupon_type])
      @cupon_type.type = params[:cupon_type][:type].to_sym
    

    Note the .to_sym that overrides the first creation on the object (in my case it was coupons).

    Now you can use it like this:

    c.type == :type_one
    c.type = :type_two
    
    0 讨论(0)
  • 2020-12-24 05:27
    t.enum :file_type ,:limit => [:jpg, :png, :gif] ,:default => :gif
    
    0 讨论(0)
  • 2020-12-24 05:29

    This will also work....

    add_column :table_name, :column_name, "enum('abc','def','ghi')", :default => 'abc'

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