简体   繁体   中英

How to define boolean field for a rails migration

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

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.

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

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

Change the type attribute to :boolean and run rake db:migrate again. You should be able to call, for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM