如何将枚举作为字符串存储到Rails中的数据库 [英] How to store enum as string to database in rails

查看:42
本文介绍了如何将枚举作为字符串存储到Rails中的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ruby中创建迁移,其中默认值是字符串而不是Integer,所以我想将枚举存储到数据库中,但是我不想将其存储为Integer,因为那样对另一个要使用相同表的应用程序。我该怎么做 default: female 而不是 default:0

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, because then it does not make sense to another application that wants to use the same table. How do I do default: "female" instead of default:0

class AddSexToUsers < ActiveRecord::Migration
  def change
    add_column :users, :sex, :integer, default: 0
  end
end
class User < ActiveRecord::Base
  enum sex: [:female, :male]
  has_secure_password
end

I

推荐答案

阅读 枚举 文档,您可以看到 Rails 使用的值索引 Array 解释为:

Reading the enum documentation, you can see Rails use the value index of the Array explained as:


请注意,使用数组时,隐式从值到数据库整数的映射是根据值在数组中出现的顺序得出的。

Note that when an Array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array.

但是也说明您可以使用哈希

But it is also stated that you can use a Hash:


还可以使用哈希显式映射属性和数据库整数之间的关系。

it's also possible to explicitly map the relation between attribute and database integer with a Hash.

例如:

class Conversation < ActiveRecord::Base  
  enum status: { active: 0, archived: 1 }  
end

所以我使用 Rails 4.2.4 sqlite3 进行了测试,并创建了一个 User 类,该类的 string 类型用于 sex 类型,在枚举中包含哈希 带有 string 值(我使用的是 fem mal 值,与 female不同 male ):

So I tested using Rails 4.2.4 and sqlite3 and created an User class with a string type for sex type and a Hash in the enum with string values(I am using fem and mal values to differ from female and male):

迁移:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :sex, default: 'fem'
    end
  end
end  

型号:

class User < ActiveRecord::Base
  enum sex: { female: 'fem', male: 'mal' }
end

并在控制台中:

u = User.new
#=>  #<User id: nil, sex: "fem">
u.male?
#=> false
u.female?
#=> true
u.sex
#=> "female"
u[:sex]
#=> "fem"
u.male!
# INSERT transaction...
u.sex
#=> "male"
u[:sex]
#=> "mal"

这篇关于如何将枚举作为字符串存储到Rails中的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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