How to store enum as string to database in rails

前端 未结 5 1082
广开言路
广开言路 2021-02-05 07:46

How do I create a migration in ruby where the default is a string rather than an Integer, I want to store enum into the database, but I do not want to store it as Integer, becau

5条回答
  •  独厮守ぢ
    2021-02-05 08:27

    enum in Rails and ENUM type in MySQL are 2 different things.

    1. enum in Rails is just a wrapper around your integer column so it's easier for you to use strings in queries, rather than integers. But on database level it's all converted to integers (automatically by Rails), since that's the type of the column.

    2. ENUM type in MySQL is vendor-specific column type (for example, SQLite doesn't support it, but PostgreSQL does). In MySQL :

    An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.

    CREATE TABLE shirts (
        name VARCHAR(40),
        size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
    );
    INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),
      ('polo shirt','small');
    SELECT name, size FROM shirts WHERE size = 'medium';
    +---------+--------+
    | name    | size   |
    +---------+--------+
    | t-shirt | medium |
    +---------+--------+
    

    For the migration, you need to do this:

    class AddSexToUsers < ActiveRecord::Migration
      def change
        add_column :users, :sex, "ENUM('female', 'male') DEFAULT 'female'"
      end
    end
    

提交回复
热议问题