[RUBY] Utilization of Rails Boolean type

Introduction

I was making an original app and used the Boolean type for the first time. Write down the usage and precautions as a memorandum. The type of the column (column name: status, table name: suggestions) used for status judgment is boolean.

Development environment ruby 2.6.5 Rails 6.0.3.4

table of contents

  1. Migration file
  2. Model
  3. Data storage

1. Migration file

Set the column type to "boolean". Enforce a NOT NULL constraint with null: false to disallow empty columns.

2020***********_create_○○.rb


    create_table :suggestions do |t|
      t.boolean :status, null: false
      t.timestamps
    end

2. Model

Describe the validation in the model. Note that the description of column and empty validation is different.

○○.rb


validates :text, presence: true #<=Description of other columns
validates :status, inclusion: { in: [true, false] }

3. Data storage

Save as true or false.

@suggestion.status = true 

Reference page How to validate boolean column in Rails and return it as an error if the type is different that's all

Recommended Posts

Utilization of Rails Boolean type
Byte size of boolean type in JavaVM
[Rails] Introduction of PAY.JP
Utilization of Active Hash
Rails Tutorial/Significance of Indexing
Utilization of seed file
[Rails] Addition of columns / Change of data type / column name
Rails implementation of ajax removal
[Rails] Introduction of devise Basics
What is a boolean type?
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Rails reference type creation added
[Rails] Implementation of tutorial function
[Rails] Implementation of like function
[Rails] Japanese localization of error messages
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
[Rails] Implementation of user logic deletion
[Rails] Asynchronous implementation of like function
Summary of rails validation (for myself)
[Rails] List instances of multiple models
[Rails] Introduction of Rubocop by beginners
[Rails] Check the contents of the object
[Rails] Implementation of image preview function
Basic knowledge of Ruby on Rails
Explanation of the order of rails routes
Kaminari --Added pagination function of Rails
[Rails] About implementation of like function
[Rails] Implementation of user withdrawal function
[Rails] Implementation of CSV export function
[Rails] Summary of complicated routing configurations
Check the migration status of rails
What is a column Boolean type?
Japanese localization of error messages (rails)
[Rails] Implementation of many-to-many category functions
[Rails] Differences and usage of each_with_index and each.with_index
[Java] Correct comparison of String type
[Rails] Types of associations (one-to-many / many-to-many)
[Specific usage of before_action] Rails refactoring