Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 488
lkahtz Avatar asked Feb 04 '11 08:02

lkahtz


People also ask

How do you define a boolean in Ruby?

In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .

How do I migrate a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename. For example, to migrate to the migration 20160515085959_add_name_to_users. rb , you would use 20160515085959 as the version number.

What is Boolean field?

The Boolean input field enables users to input a “true” or “false” value in an entry. When you add this field in content type, it reflects as a checkbox in the entry page. This field possesses certain properties that you can change any time as per your needs.


1 Answers

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

like image 68
sevenseacat Avatar answered Sep 17 '22 17:09

sevenseacat