简体   繁体   中英

How can I change_column_default based on the value selected of another row in a Ruby on Rails migration?

Sorry, y'all. New to Ruby on Rails. I am updating a profile form that consists of the following YES/NO questions: 在此处输入图像描述

The user table already has an existing children_under_five column but I'd like to add a column has_children to incorporate whether they have children at all. The only new field will be has_children which, in the event, someone has a child under 5 that means they have a child, so has_children should be true for those folks, otherwise it should default to false . How can I implement this within the migration itself? This is all I have so far:

  def change
    add_column :users, :has_children, :boolean, default: false, null: false
  end
end

Add an update statement either in that migration or a following one...

 def change
   query = <<-SQL
     update users
     set has_children = children_under_five
   SQL

   execute query
 end

How about using a method here?

class User < ApplicationRecord
  def has_children?
    self.children_under_five > 0 ? true : false
  end
end

And you can use it as

>> user = User.first
   user.has_children? # returns true or false

I quite dont understand your question but the question is? How to add a column with migration? well: rails g migration add_has_children_to_users has_children:boolean then rails db:migrate

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