在rails中创建带有数据库迁移的集合列

发布于 2024-08-29 11:07:06 字数 127 浏览 0 评论 0原文

我需要向数据库中的用户表添加一个新列。我想要设置列的类型。该列代表用户的性别。该集合应该有两个选项。一种代表男性“m”,另一种代表女性“f”。

但我还没有找到任何用于添加具有设置类型的列的文档。

我该怎么做?

I need to add a new column to my users table in the database. I want the type of the column to be set. The column represents the users gender. There should be two options to the set. One form Male "m" and the other for Female "f".

But I haven't found any documentation for adding a column with the set type.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瀟灑尐姊 2024-09-05 11:07:06

使用什么数据库? mysql?如果你想使用 SET 数据类型,你必须手动完成,因为 Rails 不支持它。然而,我这样做只是

t.string :gender, :limit => 1

为了方便。

What db is used? mysql? If you're want to use SET datatype, you'll have to do it manually, as rails doesn't support it. However, I'd do just

t.string :gender, :limit => 1

for the sake of convenience.

空心空情空意 2024-09-05 11:07:06

在您的用户模型中,您应该添加以下行来要求 M/F 答案。

validates_inclusion_of :gender, :in => %w( m f M F)

In your Users model, you should add the following line to require M/F answers.

validates_inclusion_of :gender, :in => %w( m f M F)
山色无中 2024-09-05 11:07:06

我认为你想添加带有默认数据类型的性别列(如果我错了,请纠正我),如果是这样,这里会有一个步骤,

我假设“M”代表男性,“F”代表女性(你如果您愿意,也可以使用整数)

创建迁移

ruby script/generate migration add_gender_column_to_users

这将为您创建一个迁移,顾名思义,它将

在您的迁移 self.up 操作中

add_column :users, :gender, :string, :default => 'm'

的用户表中添加一个性别列,在这里添加它,它表示我们正在添加性别字符串类型的列,其默认值为“m”,

并将其添加到 self.down 事件中

remove_column :users, :gender

,这样您的最终迁移将看起来像这样

class AddGenderColumnToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :gender, :string, :default => 'm'
  end
  def self.down
    remove_column :users, :gender
  end
end

,就

rake db:migrate

这样,希望这有帮助

I think you want to add the gender column with a default datatype (correct me if I'm wrong), If so there would be the step

here I'm assuming 'M' is for male and "F" is for female (you can use integers also if you wish)

create a migration

ruby script/generate migration add_gender_column_to_users

This will create a migration for you and as the name implies it will add a gender column to your users table

in your migrations self.up action add this

add_column :users, :gender, :string, :default => 'm'

here it says we are adding a gender column of string type and its default values is 'm'

and add this to self.down events

remove_column :users, :gender

so your final migration will look something like this

class AddGenderColumnToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :gender, :string, :default => 'm'
  end
  def self.down
    remove_column :users, :gender
  end
end

and do a

rake db:migrate

thats it, hope this helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文