Ruby-on-rails 如何为 rails 迁移定义布尔字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4896169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:19:23  来源:igfitidea点击:

How to define boolean field for a rails migration

ruby-on-rails

提问by lkahtz

I want to add a boolean value field ("is_public") to the table "my_model". Currently I can use this:

我想向表“my_model”添加一个布尔值字段(“is_public”)。目前我可以使用这个:

class AddPublicToDream < ActiveRecord::Migration
  def self.up
    add_column :my_model, :is_public, :string
  end

  def self.down
    remove_column :my_model, :is_public, :string
  end

end

Then I can assign "true" or "false" to mymodel.is_public in controllers.

然后我可以在控制器中为 mymodel.is_public 分配“true”或“false”。

Can I substitute :string with :boolean to achieve the same effect? Would it save some database space comparing to :string?

我可以用 :boolean 替换 :string 来达到同样的效果吗?与 :string 相比,它会节省一些数据库空间吗?

回答by sevenseacat

Yes, you can use :booleanfor this, and yes it will also save database space.

是的,您可以:boolean为此使用它,是的,它还可以节省数据库空间。

回答by Kleber S.

Change the type attribute to :booleanand run rake db:migrateagain. You should be able to call, for example:

将类型属性更改为:booleanrake db:migrate再次运行。您应该能够调用,例如:

Dream.is_public?  # returning true or false depending whether is set.