0

Sorry, y'all. New to Ruby on Rails. I am updating a profile form that consists of the following YES/NO questions: enter image description here

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
sbuck89
  • 123
  • 3
  • 6

3 Answers3

2

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
dbugger
  • 15,868
  • 9
  • 31
  • 33
0

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
muskrat_
  • 101
  • 7
-1

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